高手帮忙!简单C语言题目,谢谢

来源:百度知道 编辑:UC知道 时间:2024/05/30 05:36:43
题目:编写程序!统计一个字符串中单词的个数,单词之间以空格间隔!

这个应该是谭浩强课本上的原题。就是碰到新的单词就开始计数。单词开始以前一字符是空格,当前字符不是空格计算。

#include <stdio.h>
void main()
{
char string[81];
int i;
int num = 0; /* 统计单词个数 */
int word = 0; /* 是否为单词的标示 */
char c;

gets(string);

for (i = 0; (c = string[i]) != '\0'; i++)
{
if (c == ' ')
word = 0;
else
if (word == 0)
{
word = 1;
num++;
}
}
printf("\nThere are %d words int the line.\n", num);
}