关于找字符串中有多少单词

来源:百度知道 编辑:UC知道 时间:2024/05/29 11:31:24
以下是源码
其中的
if (c == ' ')
word = 0;
else
if (word == 0)
{
word = 1;
num++;
}
我不明白
有没有人可以解释一下

============================

#include <stdio.h>
int 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);
return 0;
}
谢谢

假如这个字符串是"I am a man"

这个for循环里面逐个取出字符串里的字符

if (c == ' ') //如果取出的字符是空格
word = 0; //那么标记这个不是单词
else
if (word == 0) //因为在英语语法中
{ //写完一个单词要写一个空格
word = 1; //所以如果检测到这个是空格,
num++; //那么前面肯定已经有一个单词
} //所以num++,并把word标记=1