您的位置:首页 > 其它

统计字符串中单词的个数

2016-02-10 18:56 429 查看

Description

输入一行字符(少于300个字符),以回车结束,统计其中单词的个数。各单词之间用空格分隔,空格数可以是多个。

Input

输入一字符串,以回车结束。

Output

输出该字符串中单词的个数

Sample Input

This is a c program.

Sample Output

5

#include<cstdio>
#include<cstdlib>
#include<cstring>

int main()
{
char ch;
int _count = 0;
int word = 0;
while((ch = getchar()) != '\n')//出现TLE的原因:数据里面没有出现换行符就结束了
{
if(ch == EOF)//加这行之前 出现TLE
break;
else
{
if(ch == ' ')
word = 0;
else if(word == 0)
{
word = 1;
_count++;
}
}

}
printf("%d\n" , _count);
return 0;
}


#include<cstdio>
#include<cstdlib>
#include<cstring>

char str[305];
int main()
{
while(gets(str) != NULL)
{
int _count = 0;
int word = 0;
for(int i = 0 ; str[i] != '\0' ; i++)
{
if(str[i] == ' ')
word = 0;
else if(word == 0)
{
_count++;
word = 1;
}
}
printf("%d\n" , _count);
}

return 0;
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: