题目描述
编写程序,输入一行不超过 80 个字符,统计其中有多少个单词,单词之间用空格分隔开。
输入格式
I love China!
输出格式
3
解法
定义一个标志位flag=0,遍历到第一个单词的开头时,单词数+1,标志位置1,当单词结束,遇到空格时,代表一个单词结束,标志位置0
代码示例
#include <stdio.h>
int main()
{
char ch[81];
int i, num = 0, word = 0;
char c;
gets(ch);
for (i = 0; (c = ch[i]) != '\0'; i++)
if (c == ' ') word = 0;
else if (word == 0)
{
word = 1;
num++;
}
printf("There are %d words in the line.\n", num);
return 0;
}