题记(37)--单词识别

目录

一、题目内容

二、输入描述

三、输出描述

四、输入输出示例

五、完整C语言代码


一、题目内容

输入一个英文句子,把句子中的单词(不区分大小写)按出现次数按从多到少把单词和次数在屏幕上输出来,次数一样的按照单词小写的字典序排序输出,要求能识别英文单词和句号。

二、输入描述

输入为一行,由若干个单词和句号组成

三、输出描述

输出格式参见样例。

四、输入输出示例

输入:

A blockhouse is a small castle that has four openings through which to shoot.

输出:

a:2
blockhouse:1
castle:1
four:1
has:1
is:1
openings:1
shoot:1
small:1
that:1
through:1
to:1
which:1

五、完整C语言代码

AC代码~

#include
#include
typedef struct str {
    char s[20];
    int count;
} word;

void Sort(word a[], int n) {
    for (int i = n - 1; i > 0; i--) {
        for (int j = 0; j < i; j++) {
            if (strcmp(a[j].s, a[j + 1].s) > 0) {
                word tmp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = tmp;
            }
        }
    }
}

void strcopy(char* s1, char* s2, int n) {
    for (int i = 0; i < n; i++)
        s1[i] = s2[i];
    s1[n] = '\0';
}

int strcompare(char* s1, char* s2, int n) {
    for (int i = 0; i < n; i++)
        if (s1[i] != s2[i])
            return 0;
    return 1;
}
word a[1000];
int top = 0;
int main() {
    for (int k = 0; k < 1000; k++)
        a[k].count = 0;
    char s[1000];
    gets(s);
    int i = 0;
    while (s[i] != '.') {
        if ('A' <= s[i] && s[i] <= 'Z')
            s[i] = s[i] + 32;
        char tmp[20];
        int j = 0;
        while (s[i] != ' ') {
            if (s[i] == '.')
                break;
            if ('A' <= s[i] && s[i] <= 'Z')
                s[i] = s[i] + 32;
            tmp[j] = s[i];
            j++;
            i++;
        }
        int k;
        for (k = 0; k < top; k++) {
            if (strcompare(a[k].s, tmp, j) == 1) {
                a[k].count++;
                break;
            }
        }
        if (k == top) {
            strcopy(a[top].s, tmp, j);
            a[k].count++;
            top++;
        }
        if (s[i] != '.')
            i++; // 跳过空格
    }
    Sort(a, top);
    for (i = 0; i < top; i++)
        printf("%s:%d\n", a[i].s, a[i].count);
    return 0;
}

你可能感兴趣的:(c++)