PTA 7-26 单词长度(15 分)

PTA 7-26 单词长度 (15分)

  你的程序要读入一行文本,其中以空格分隔为若干个单词,以.结束。你要输出每个单词的长度。这里的单词与语言无关,可以包括各种符号,比如it's算一个单词,长度为4。注意,行中可能出现连续的空格;最后的.不计算在内。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 int main()
 5 {
 6     char str[1000];
 7     gets(str);      ///输入字符串
 8     int len = strlen(str);    ///len记下字符串的长度,不包括''
 9     int sp = 0;     ///sp记录空格的个数
10     int ch = 0;     ///ch记录新字符的个数
11     for(int i = 0; i < len-1 ; ++i)
12     {
13         if(str[i] != ' ')   ///如果不是空格
14         {
15             if(ch && sp)    ///如果空格数和字符数都未清零
16             {
17                 printf("%d ", ch);
18                 ch = 0;
19             }
20             ++ch;
21             sp = 0;
22         }
23         else
24         {
25             ++sp;           ///如果是空格,sp加1
26         }
27     }
28     if(ch)      ///若还有字符的个数未输出
29     {
30         printf("%d", ch);
31     }
32     return 0;
33 }

题目来源:https://pintia.cn/problem-sets/14/problems/806

原文地址:https://www.cnblogs.com/yudashuai/p/12465040.html