1397 - 统计单词
编一个程序,读入用户输入的,以“.”结尾的一行文字,统计一共有多少个单词,并分别输出每个单词含有多少个字符。
(凡是以一个或多个空格隔开的部分就为一个单词)
Input
输入包括1行字符串,以“.”结束,字符串中包含多个单词,单词之间以一个或多个空格隔开。
Output
可能有多组测试数据,对于每组数据,
输出字符串中每个单词包含的字母的个数。
Examples
Input
hello how are you.
Output
5 3 3 3
Solution C
#include<stdio.h> #include<string.h> void main() { char a[1100]; while(gets(a)) { int i,j,k,l,m=0,n=0,b[1100]; for(i=0; i<strlen(a); i++) { if(a[i]!=' '&&a[i]!='.') n++; if(a[i]==' '||a[i]=='.') { i++; while(a[i]==' ') { i++; } m++; i--; if(m==1) printf("%d",n); else printf(" %d",n); n=0; } } printf("\n"); } }
Solution C++
#include <stdio.h> #include <string.h> int main(){ char str[1000]; // 用来读取整个字符串 char *pStr; // 一个字符指针,用来存储以空格和点号分割的字符串 while(gets(str)){ pStr = strtok(str, " ."); // 先用空格和点号作一次切割 int iCount = 0; // 记录已经有多少数字输出了,由于每个数字间用一个空格分开,因而需要记录数字的输出数目 while(pStr){ if(iCount++){ putchar(' '); // 数字间使用一个空格分割 } printf("%d", strlen(pStr)); // 输出单词的长度 pStr = strtok(NULL, " ."); // 做下一次分割 } putchar('\n'); // 别忘了换行 } return 0; }