统计单词

题目:编一个程序,读入用户输入的,以“.”结尾的一行文字,统计一共有多少个单词,并分别输出每个单词含有多少个字符。 (凡是以一个或多个空格隔开的部分就为一个单词) 

思路:

设置一个char变量ch逐个读取缓存中的字符;

设置一个数组countV计算每一个单词中字符的数字;

设置一个flag控制多个连续空格的情况;

由于用scanf读入数据,换行符也会被读入,需要加入一个getchar吞掉多余的换行符。

 1 #include<stdio.h>
 2 #include<string.h>
 3 int main()
 4 {
 5     char ch;
 6     int len=0,i=0,j;
 7     int flag=0;//用于判断是否出现【前一个字符为空格,当前为字符】的情况。从而记录字符的数组位置后移+1;
 8     int countV[101];
 9     memset(countV,0,sizeof(countV));
10     while(scanf("%c",&ch)!=EOF)
11     {
12         if(ch!='.')
13         {
14             if(ch!=' '&&flag==0)
15             {
16                 countV[i]++;
17             }
18             else if(ch!=' '&&flag==1)//若前一个为空格,当前为字符
19             {
20                 flag=0;
21                 i++;
22                 countV[i]++;
23             }
24             else
25             {
26                 flag=1;
27             }
28         }
29         else
30         {
31             for(j=0; j<=i; j++)
32             {
33                if (countV[j]!=0)
34                {printf("%d",countV[j]);
35                 if(j==i)printf("\n");
36                 else printf(" ");
37                }
38             }
39             memset(countV,0,sizeof(countV));
40             i=0;
41             flag=0;
42             getchar();//用scanf缓存中会有一个回车,这里要吞掉它。
43         }
44     }
45     return 0;
46 }

 

posted @ 2018-01-16 17:33  -DP-  阅读(158)  评论(0编辑  收藏  举报