輸入:char(需要在陣列中的words中找到出現次數最多的這個字符)
輸出:如果出現次數相同,則列印給定字符或單詞出現次數最多的單詞。
需要找到給定字符出現次數最多的一個或多個單詞。
我撰寫了一個程式來查找并列印出現次數最多的單詞。但我不明白如何用給定的字符找到單詞。
#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”
我為我的英語感到抱歉。
uj5u.com熱心網友回復:
這是您的問題的解決方案,它嘗試盡可能少地更改您的代碼:
#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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/344353.html
上一篇:一萬粉的時候,我爬光了我所有的粉絲,只為驗證一個事情
下一篇:具有1個回圈的函式的復雜性
