/*程序功能:从键盘输入一行字,统计以a-z开头的单词个数*/
#include<stdio.h>
main()
{
char *s,b[200];
int a[26],words=0;
int i,flag=0;
s=b;
for(i=0;i<26;i++)
a[i]=0;
gets(s);
printf("%s",s);
printf("\n");
*s=' ';
while(*s!='\0')
{
flag=0;
if(*s==' ')
{
flag=1;
words++;
}
if(flag)
{
s++;
for(i=0;i<26;i++)
if(*s==97+i)
a[i]++;
}
s++;
}
printf("You have input %d words\n",words+1);
for(i=0;i<10;i++)
printf("word with %c begin have %d\n",i+97,a[i]);
}
另一种解法:
#include<stdio.h>
#include<string.h>
void main()
{
int sum=0;
char sentence[200],*p;
p=sentence;
int i;
int count[27]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
gets(p);
while(*p!='\n')
{
while(*p==' ')
{
p++;
}
count[*p-96]++;
while(*p!=' '&&*p!='\n')
{
p++;
}
}
printf("the word's number is:%d\n",count[0]);
for(i='a';i<='z';i++)
{
printf("%c: %d\n",i,count[i-96]);
sum+=count[i-96];
}
printf("the word's number is:%d\n",sum);
}
在来一个:
#include "stdio.h"
void main()
{
char a = '0', b, str[255];
int i = 0, numWord = 0, numLetter[26];
printf("input a string:\n");
gets(str);
for(i=0;i<26;i++)
numLetter[i]=0;
i=0;
while (str[i] != '\0')
{
b = str[i];
if (((a < 'A' || a > 'Z') && (a < 'a' || a > 'z')) &&
((b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z')))
{
numWord++;
if (b >= 'a')
numLetter[b-'a']++;
else
numLetter[b-'a']++;
}
i++;
a = b;
}
printf("the number of the words is %d\n",numWord);
for(i=0;i<26;i++)
printf("the number of the words beginning with %c or %c is %d\n",i+'a',i+'A',numLetter[i]);
}