#include<stdio.h>
#include<string.h>
int main()
{
char str[100], c;
int i, num = 0, word = 0;
int len = strlen(str);
printf("请输入字符串:\n");
gets_s(str);
for (i = 0; (c = str[i]) != '\0'; i++)
{
if (c == ' ')
word = 0;
else if (word == 0)
{
word = 1;
num++;
}
}
printf("单词总数为:%d. \n", num);
printf("字符串长度为:%d", len);
return 0;
}
题目:编程实现输人一个含空格的宇符串,统计其中有多少个单词(空格分隔单词),输出单词个数和字符串长度。(注意:测试最后是空格和不是空格两种情况。)
运行效果:
请输入一个英文句子:
Hellow how are you?
单词个数:4
字符串长度:18
请输入一个英文句子:
Hellow how are you? (空格)
单词个数:4
字符串长度 19