输入: 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“
我为我的英语感到抱歉。
发布于 2021-11-01 19:23:42
以下是您的问题的一个解决方案,它试图尽可能少地更改您的代码:
#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
。
https://stackoverflow.com/questions/69801387
复制相似问题