7-2 统计一行文本的单词个数 (15 分)

7-2 统计一行文本的单词个数 (15 分)
本题目要求编写程序统计一行字符中单词的个数。所谓“单词”是指连续不含空格的字符串,各单词之间用空格分隔,空格数可以是多个。

输入格式:
输入给出一行字符。

输出格式:
在一行中输出单词个数。

输入样例:
Let’s go to room 209.
输出样例:
5

#include<stdio.h>  
  
int main()  
{  
    char str[1001];  
    gets(str);  //输入字符串
    int count=0;  
    int i=0;  
    while(str[i]==' ') //如果开头有空格的话就会跳过开头的空格,并且i会增加 
        i++;  
    while(str[i]!='\0')  //直到读取到\0跳出循环
    {  
        if(str[i]!=' ') //如果是空格,每个空格都会跟着一个单词,但不一定只有一个空格
        {   
            count++;  
            while(str[i]!=' ') //跳过一个空格后的所有空格
            {  
                if(str[i]=='\0')  //如果出现\0说明到达末尾直接结束break跳出while循环
                    break;  
                i++;      
            }  
        }  
        else  
        {  
            while(str[i]==' ' )  
                i++;      
        }  
    }  
    printf("%d\n",count);  
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43382350/article/details/84776551