首页 > 试题广场 >

统计单词

[编程题]统计单词
  • 热度指数:17596 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
编一个程序,读入用户输入的,以“.”结尾的一行文字,统计一共有多少个单词,并分别输出每个单词含有多少个字符。 (凡是以一个或多个空格隔开的部分就为一个单词)

输入描述:
输入包括1行字符串,以“.”结束,字符串中包含多个单词,单词之间以一个或多个空格隔开。


输出描述:
可能有多组测试数据,对于每组数据,
输出字符串中每个单词包含的字母的个数。
示例1

输入

hello how are you.

输出

5 3 3 3
#include <stdio.h>

int main() {
    int c;
    int count=0;
    while ((c=getchar())!='.') {
        if (c!=' ') {
            count++;
        }
        else {
            printf("%d ",count);
            count=0;
        }
    }
    printf("%d",count);
    return 0;
}


编辑于 2024-01-30 16:19:54 回复(1)
#include <stdio.h>
#include <stdlib.h>
int main() {
    char s[100];
    int t, count, f;
    while (gets(s) != NULL) { //重点 用NULL判断而不是EOF
        t = 0;
        count = 0;
        f = 0;
        while (s[t] != '\0') { //'\0'字符串的结束符
            if (s[t] == '.' && count != 0) {
                printf(" %d\n", count);
                count = 0;
            } else if (s[t] != ' ')
                count++;
            else if (count != 0) {
                if (f == 0) {
                    f = 1;
                    printf("%d", count);
                } else
                    printf(" %d", count);
                count = 0;
            }
            t++;
        }

    }
    return 0;

}
发表于 2023-01-17 21:33:56 回复(0)
不知道为什么这道题难度是较难
#include<stdio.h>
#include<string.h>

char s[1000];
int main() {
    int i,count;
    while(gets(s) != NULL) {
        i = 0, count = 0;
        while(i < strlen(s)) {
            if(s[i] != ' ' && s[i] != '.') {
                count++;
                i++;
            }
            else {
                printf("%d ",count);
                count = 0;
                i++;
            }
        }
    }
}


发表于 2022-03-13 21:59:41 回复(0)
#include<stdio.h>
int main(void)
{
    char str[50];
    scanf("%[^\n]",str);
    int i = 0,r = 0;
    while (str[i] != '.')
    {
        if(str[i] != ' ')
        {
            r++;
        }
        else
        {
            printf("%d ",r);
            r = 0;
        }
        i++;
    }
    printf("%d\t",r);
    return 0;
}

发表于 2021-11-05 15:06:21 回复(0)

问题信息

难度:
5条回答 13031浏览

热门推荐

通过挑战的用户

查看代码