天天看点

统计单词 UESTC - 60

统计单词 UESTC - 60

Problem

编写一个函数,该函数能够统计一个英文字符串中有多少个单词。

Input

第一行是整数nn,表示测试的数据组数,下面是nn行含空格的字符串(仅由空格和英文字符组成,长度不超过200)。

Output

每行输入对应一行输出,表示对应行有多少单词。

Sample Input

1

I am a student

Sample Output

4

ps:字母+空格 肯定有一个单词,回车另算

代码如下:

#include<iostream>  
#include<cstdio>  
#include<cstring>  
#include<algorithm> 
#include<string.h> 
using namespace std; 
int main () {
    int t;
    scanf("%d", &t);
    getchar(); //消除回车影响 
    while( t-- ) {
        char str[];
        gets(str);
        int len = strlen(str);
        int sum = ;
        for(int i = ; i <= len; i++) {
            if((str[i]>='a' && str[i]<='z')||(str[i]>='A' && str[i]<='Z'))
                continue;//判断第一个空格前一位是不是字母,存在多空格的情况 
            if((str[i-]>='a' && str[i-]<='z')||(str[i-]>='A' && str[i-]<='Z')||str[i-]=='\n')
                sum++;
        }
        printf("%d\n", sum);
    }
    return ;
}