HUELOJ:136 单词个数统计

题目描述
从键盘输入一行字符,长度小于 1000。统计其中单词的个数,各单词以空格分隔,且空格数可以是多个。

输入描述
输入只有一行句子。仅有空格和英文字母构成

输出描述
单词的个数

输入样例

stable marriage  problem Consists     of Matching members

输出样例

7

代码一

#include
#include
int main()
{
	char str[1000];
	int len = strlen(str);
	fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';
    int count = 0;
    for(int i = 0;str[i]!='\0';i++)
    {
    	if(str[i] != ' '&&str[i+1] == ' ')
    	count++;
	}
	if(str[len-1]!=' ')
	count++;
	printf("%d\n",count);
	return 0;
}

代码二

#include
#include
int main()
{
    char str[1000];
    fgets(str, sizeof(str), stdin);//用fgets输入更安全
    str[strcspn(str, "\n")] = '\0';//去掉 fgets 可能读取的换行符
    int count = 0;
    int InWord = 0;//标记是否在单词中
    for(int i = 0;str[i]!='\0';i++)
    {
        if(str[i]==' ') {
            InWord = 0;//标记不在单词中
        }
        else if(InWord == 0) {
            InWord = 1;
            count++;
        }
    }
    printf("%d\n",count);
    return 0;
} 

你可能感兴趣的:(HUEL-OJ,算法,c语言)