判断一个单词:需要遍历输入的字符,前一个字符非空格,后一个字符为空格或者\0是认定为一个单词
了解可能输入的情况:
1.how are you --开头无空格,各单词之间只含一个空格
2. how are you --开头有空格
3.how are you 各单词之间含多个空格
具体代码实现:
#include<stdio.h>
#include<string.h>
int main()
{
char a[20];
int n,count= 0;
int i = 0;
printf("输入一行字符:"); // akd skcpw skcp \0
gets(a);
n = strlen(a);
while(i<n)
{
if (a[i] != ' ' && (a[i + 1] == ' ' || a[i + 1] == '\0'))
{
count++;
}
i++;
}
printf("单词个数为:%d\n", count);
return 0;
}