1133: 单词个数统计
题目描述
从键盘输入一行字符,长度小于1000。统计其中单词的个数,各单词以空格分隔,且空格数可以是多个。
输入
输入只有一行句子。仅有空格和英文字母构成
输出
单词的个数
样例输入 Copy
stable marriage problem Consists of Matching members
样例输出 Copy
7
代码
#include<stdio.h>
#include<ctype.h>
#include<string.h>
int main()
{
int i,len,sum=0;
char str[1000];
gets(str); //输入字符串
len=strlen(str);
for(i=0;i<len;i++)
{
if(isalnum(str[i])&&str[i+1]==' ')
sum++;
}
if(isalnum(str[len-1])) //考虑到最后一个单词后没有空格的习惯
sum++;
printf("%d\n",sum);
return 0;
}
代码
#include<stdio.h>
int main()
{
int i,count;
char str[1000];
gets(str); //输入字符串
count=0;
for(i=0;str[i]!='\0';i++)
{
if(str[i]==' '&&str[i+1]!=' ')
count++;
}
if(str[0]!=' ') count++; //考虑第一个字符不是空格的情况
if(str[i-1]==' ') count--; //考虑到最后一个单词后没有空格的情况
printf("%d\n",count);
return 0;
}