首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何查找包含给定字符次数最多的所有单词

如何查找包含给定字符次数最多的所有单词
EN

Stack Overflow用户
提问于 2021-11-01 18:43:27
回答 1查看 48关注 0票数 0

输入: char (需要在数组中找到此char在单词中出现的最多次数)

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

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

我写了一个程序来查找和打印出现次数最多的单词。但是我不能理解如何找到带有给定字符的单词。

代码语言:javascript
运行
复制
#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“

我为我的英语感到抱歉。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-01 19:23:42

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

代码语言:javascript
运行
复制
#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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69801387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档