Home > Software design >  How to find all the words that contain a given character the most times
How to find all the words that contain a given character the most times

Time:11-02

Input: char (need to find the most number of occurrences of this char in words which is in array)

Output: print word which has the highest number of occurrences of given char or words if there are the same number of occurrences.

Need to find word or words which have the most number of occurrences of given char.

I wrote a program that finds and prints the word with the highest number of occurrences. But I can't understand how to find word with given 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;
}

In this program result is word "Useuuu"

I'm sorry for my English.

CodePudding user response:

Here is a solution to your problem that attempts to change your code the least possible:

#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;
}

Explanation: In the code, instead of having a single char* word, I use a doubly-linked list to store multiple words. I iterate through each word and find the number of occurrences of the char. I then compare to see if the word belongs in the list.

Notes: this code is rough and could be optimized. Also, if the order of the words doesn't matter, you could use forward_list.

  • Related