Description
编写一个函数,该函数能够统计一个英文字符串中有多少个单词。
Input
第一行是整数n,表示测试的数据组数,下面是n行含空格的字符串(仅由空格和英文字符组成)。
Output
每行输入对应一行输出,表示对应行有多少单词。
Sample Input
1
I am a student
Sample Output
4
我的解法,未完善:
1 #include <stdio.h> 2 #include <string.h> 3 4 int i,j,k[1001],t; 5 char a[1001][1001]; 6 7 int main() 8 { 9 scanf("%d",&t); 10 for (i=0;i<t;i++){ 11 j=0; 12 while ((a[i][j]=getchar())!='\n'){ 13 14 j++; 15 } 16 k[i]=j; 17 } 18 19 for(i=0;i<t;i++) 20 { 21 int num=0; 22 for (j=0;j<k[i];j++) 23 { 24 if ((a[i][j]==' ')&&(a[i][j-1]!=' ')) num++; 25 else continue; 26 } 27 printf("%d\n",num+1); 28 } 29 return 0; 30 }
牛逼解法:
1 #include <stdio.h> 2 #include<string.h> 3 int main() 4 { 5 int j,T; 6 scanf("%d",&T); 7 getchar(); 8 for(j=0;j<T;j++) 9 { 10 char str[100]={}; 11 int i,count = 0; 12 int flag = 0; 13 gets(str); 14 for(i=0;str[i];i++) 15 { 16 if(str[i] == ' ') 17 flag = 0; 18 else if(flag == 0) 19 { 20 flag = 1; 21 count++; 22 } 23 } 24 printf("%d\n",count); 25 } 26 27 return 0; 28 }