【问题标题】:How to find all the words that contain a given character the most times如何找到包含给定字符最多的所有单词
【发布时间】:2025-12-27 02:40:12
【问题描述】:

输入:char(需要找到这个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”

对不起我的英语。

【问题讨论】:

  • @panilya - 继续 Input: char 怎么样?
  • @Armali 已更正
  • 我的意思是继续将 charinput 添加到您的程序中。
  • 这对我来说似乎是一个太多的循环,我不确定最里面的 for 循环如何帮助你。首先,您需要一个 char 进行比较(大概应该是 c,但您没有捕获用户输入)。一旦你这样做了,你就有了buf中的当前单词,逐个字符地循环遍历该字符,与c进行比较。在一场比赛中增加一个计数器,与以前的最大值相比。如果该计数与之前的最大值匹配,则将.push_back(buf) 指向一个向量。如果有新的最大计数,请清除缓冲区和.push_back(buf)
  • @yano 谢谢,它工作了

标签: c++ arrays string algorithm char


【解决方案1】:

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

#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,而是使用双向链表来存储多个单词。我遍历每个单词并找到 char 的出现次数。然后我比较一下这个词是否属于列表。

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

【讨论】:

    最近更新 更多