Count each word in a string C++ – Using map

C++ program to count each word in a string. STL std::map will be used to filter and count word occurrences in C++ program in the string.

Note that this problem is different than count number of words in string in which we identify how many total words a string contains. In above problem each word count will be determined.

For example, count of each word in a string e.g. “hello world !!! hello world !!! good day” will be as given below.
!!!     2
day     1
good    1
hello   2
world   2

Count word occurrences C++ Code

#include <map>

using namespace std;

void wordsCount(string str){

      int count = 1;
      //key value pair map
      //key = word, value = count
      std::map<string,int> wordsMap;

      //extract words and push in map
      istringstream wordStream(str);

      string word;
      //Extract each words and add to map
      //if it does not exist in map
       while(wordStream >> word){
             //create a pair of map and bool
             pair<map<string,int>::iterator,bool> retrunValue;

             //insert element
            retrunValue = wordsMap.insert( pair<string,int>(word,count));

            //Check if map contains value
            if (retrunValue.second==false)
                  //Element already exists

       //Iterate elements and print words 
       map<string,int>::iterator itr ;

       for (itr = wordsMap.begin(); itr != wordsMap.end(); ++itr){

               cout << '\t' << itr->first ;
               cout<< '\t' << itr->second << '\n';

int main(){

      wordsCount("hello world !!! hello world !!! good day");    

      return 0;


!!! 2
day 1
good 1
hello 2
world 2

Related Posts