如何查找文本中包含指定字符出现次数最多的单词?
功能实现修改方案
核心修改点
- 新增指定字符的输入逻辑,获取需要统计的目标字符
- 移除原代码中统计单词内任意字符重复次数的双重循环,改为仅统计目标字符在当前单词中的出现次数
- 替换单个单词存储逻辑,使用动态容器存储所有符合最高出现次数的单词,解决多结果输出需求
修改后完整代码
#include <iostream> #include <cstring> #include <vector> using namespace std; int main() { char array[]="this is text. Useuuu it for test. Text for test."; // 输入要统计的指定字符 char target; cout << "请输入要查询的指定字符: "; cin >> target; char* buf = strtok(array," .,!?;:"); vector<char*> result_words; int max_count = 0; while(buf) { int n = strlen(buf); int current_count = 0; // 统计当前单词中目标字符的出现次数 for(int i = 0; i < n; i++) { if(buf[i] == target) { current_count++; } } // 更新最大次数和结果列表 if(current_count > max_count) { max_count = current_count; result_words.clear(); result_words.push_back(buf); } else if(current_count == max_count && max_count != 0) { result_words.push_back(buf); } buf = strtok(0," .,!?;:"); } // 输出结果 if(result_words.empty()) { cout << "Result: 没有找到包含指定字符的单词" << endl; } else { cout << "Result: "; for(int i=0; i<result_words.size(); i++) { if(i>0) cout << "、"; cout << result_words[i]; } cout << endl; } return 0; }
效果说明
代码默认区分字符大小写,比如输入指定字符u时运行输出结果为Useuuu,和原代码运行结果一致;如果输入指定字符t,会自动输出所有t出现次数相同的最高频单词。
内容的提问来源于stack exchange,提问作者panilya
相关产品推荐
相关产品推荐

