Find the most frequent word in a string in C++

In this tutorial, we will learn about how to find the most frequent word in a string in C++. So, continue through the article.

Introduction

The string is a collection of words that may or may not have meaning in it.

Maps are the containers that store elements in it.
Values are stored in key-value pairs, pairs are sorted and stored in it.
Each key is distinctive and cannot be changed, Only the values linked to those keys can be changed.

Find the most frequent word in a string in C++

Now, let us write the code to illustrate the same.

#include <map>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    istringstream input("C++ is a programming language. C++ follows OOPS.");
    map<string, int> count;
    string word;
    decltype(count)::const_iterator most_occurring;
    while (input >> word)
    {
        auto itr = count.emplace(word, 0).first;
        ++itr->second;
        if (count.size() == 1 || itr->second > most_occurring->second)
            most_occurring = itr;
    }
    cout <<"The Word '";
    cout << most_occurring->first << "' is repeated ";
    cout << most_occurring->second << " times\n";
}

And the output of our program is:

The Word ‘C++’ is repeated 2 times

Explanation of the program:

In the following code,
Header file <map> is used to declare the map containers.
Header file <sstream> is used to declare istringstream. istringstream is the input string stream.
We declare the string first, we then count the most used word in the string, then we print the word and its number of occurrence in the string.

I hope this will help you to solve your problem.

Also read:

String replace() function in C++

Leave a Reply

Your email address will not be published. Required fields are marked *