如何找到最多包含给定字符的所有单词

How to find all the words that contain a given character the most times

输入:char(需要在数组中的words中找出这个char出现次数最多的)

输出:打印给定字符出现次数最多的单词,或者打印出现次数相同的单词。

需要找到给定字符出现次数最多的单词。

我编写了一个程序来查找并打印出现次数最多的单词。 但是我不明白如何找到给定字符的单词。

#include <iostream>
#include <cstring>

using namespace std;
int main() {
    char array[]="this is text. Useuuu it for test. Text for test.";
    char* buf = strtok(array," .,!?;:");
    char *word;
    int max = 0;
    char c;
    while(buf) {
        int n = strlen(buf);
        for(int i = 0; i < n; i++) {
            int counter=0;
            for(int j = 0; j < n ; j++) {
                if(buf[i]==buf[j] && i != j)
                    counter++;
                if(counter>max) {
                    max=counter;
                    word=buf;
                }
            }
        }
        buf=strtok(0," .,!?;:");
    }
    cout << "Result: " << word << endl;
    return 0;
}

在这个程序中结果是单词“Useuuu”

对不起我的英语。

这里是您的问题的解决方案,它尝试尽可能少地更改您的代码:

#include <iostream>
#include <cstring>
#include <list>
using namespace std;

int main() {
    char array[]="this is text. Useuuu it for test. Text for test.";
    char* buf = strtok(array," .,!?;:");
    std::list<const char*> words{};
    
    int max = 0;
    int wrd_counter = 0;
    char c;
    std::cout << "Input char: ";
    std::cin >> c;
    while(buf) {
        int n = strlen(buf);
        int counter=0;
        for(int j = 0; j < n ; j++) {
            if(buf[j]==c)
                counter++;
        }
        if(counter>max) {
            max=counter;
            words.clear();
            words.push_back(buf);
        }
        else if(counter == max){
            words.push_back(buf);
        }
        buf=strtok(0," .,!?;:");
    }
    cout << "Results: ";
    for(const char* ccp: words){
        std::cout << ccp << " ";
    }
    return 0;
}

说明:在代码中,我没有使用单个 char* word,而是使用双向链表来存储多个单词。我遍历每个单词并找到该字符出现的次数。然后我比较一下这个词是否在列表中。

注意:这段代码比较粗糙,有待优化。另外,如果单词的顺序无关紧要,您可以使用 forward_list.