我如何计算一个单词在数组中重复的次数

How do I count the amount of times a word repeats in an array?

本文关键字:数组 一个 何计算 计算 单词      更新时间:2023-10-16

该程序使用qsort对单词进行分类。

这是我到目前为止的代码,如何计算重复单词?例如,Apple重复两次,而Main根本没有重复。

int main()
{
    //6 entries with 20 max
    char strings[6][20] = { "apple", "apple", "strawberries", "bananas", "dairy", "main" };
    qsort(strings, 4, 20, (int(*)(const void*, const void*))strcmp);
    // display the strings in ascending lexicographic order
    for (int i = 0; i < 6; i++) {
        cout << strings[i] << "n";
    }

    return 0;
}

尝试更多类似的东西:

#include <iostream>
#include <algorithm>
#include <string>
static const int max_strings = 6;
int main()
{
    //6 entries
    std::string strings[max_strings] = { "apple", "apple", "strawberries", "bananas", "dairy", "main" };
    // sort the strings in ascending order
    std::sort(strings, &strings[max_strings]);
    // display the strings and their repeat counts
    int i = 0;
    while (i < max_strings)
    {
        std::string str = strings[i];
        int count = 1;
        while (++i < max_strings)
        {
            if (strings[i] != str)
                break;
            ++count;
        }
        std::cout << "'" << str << "' appears " << count << " time";
        if (count != 1)
            std::cout << "s";
        std::cout << std::endl;
    }
    return 0;
}

输出:

"苹果"出现了2次"香蕉"出现1次"乳制品"出现1次"主"出现1次"草莓"出现1次

实时演示

相关文章: