尝试在数组中输出多个最常用的字母

问题描述

我正在尝试从文本字符串中获取一些统计信息,例如单词和句子的数量等。这些统计信息包括字符串中使用频率最高的字母。我目前正在使用以下这些函数来获取所需的大部分统计信息。

typedef struct statistics
{
    char_counts_t char_info;
    int sentences;
    int words;
    int freq[26];
    int max_freq;
    char most_freq_chars[27];
} statistics_t;

void get_letter_frequencies(const char *text,size_t len,int freq[26],int *max_freq)
{
    for (int i = 0; i < 26; i++)
        freq[i] = 0;

    for (int i = 0; i < len; i++)
    {
        if ((text[i] >= 97) && (text[i] <= 122))
            freq[text[i] - 97]++;
    }

    *max_freq = 0;
    for (int i = 0; i < 26; i++)
    {
        if (*max_freq < freq[i])
        {
            *max_freq = freq[i];
        }
    }
}


void get_text_statistics(const char *text,statistics_t *data)
{

    data->words = count_words(text,len);
    data->sentences = count_sentences(text,len);

    get_char_counts(text,len,&data->char_info);
    get_letter_frequencies(text,data->freq,&data->max_freq);


    for (int q = 0; q < 26; q++)
        data->most_freq_chars[q] = 0;

    for (int q = 0; q < 26; q++)
    {
        int max = 0;
        if (data->max_freq == data->freq[q])
        {
            data->most_freq_chars[max] = (char) (q + 97);
            max++;
        }
    }
}

现在,当尝试将统计数据制成表格时,我使用了一个 while 循环,以防万一有两个或更多字母具有相同的频率。

printf("| Most frequent letter(s)        |  [%c]  |\n",data.most_freq_chars[0]);

int a = 1;
while (data.most_freq_chars[a] != '\0')
{
printf("|                                |  [%c]   |\n",data.most_freq_chars[a]);
a++;
}

为了尝试这个场景,我输入了字符串“Hello. Goodluck!”期望得到两个最频繁的字母([o] 和 [l]),然而,只有一个出现([o])。

我该怎么做?

提前致谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)