一、题目
Description:
从键盘输入一行字符,统计其中单词的个数,各单词以空格分隔,且空格数可以是多个。
Input:
输入只有一行句子。仅有空格和英文字母构成。
Output:
单词的个数。
Sample Input:
stable marriage problem Consists of Matching members
Sample Output:
7
二、代码
#include<stdio.h>
#include<string.h>
int main()
{
/*通过统计空格来统计单词数*/
char str[100];
gets(str);
int count = 0;
for (int i = 0; str[i]!='\0'; i++)
{
if (str[i] == ' ' && str[i + 1] != ' ')
{
count++;
}
}
if (str[strlen(str) - 1] == ' ') //最后一个单词后面若还有空格不统计
{
printf("%d", count);
}
else
{
printf("%d", count + 1);
}
return 0;
}