Stringstream in C++ programming


This sample draft calculates the total number of words in a given string as well as counts the total occurrence of a particular word using stringstream in the C++ programming code. The stringstream class partners a string object with a stream enabling you to peruse from the string as though it were a stream. This code shall achieve two feats, first, it will count the total number of words then calculates the frequencies of individual words subsequently in a string using the map iterator essential methods as follows;

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int totalWords(string str){
   stringstream s(str);
   string word;
   int count = 0;
   while (s >> word)
      count++;
   return count;
}
void countFrequency(string st){
   map<string, int> FW;
   stringstream ss(st);
   string Word;
   while (ss >> Word)
      FW[Word]++;
   map<string, int>::iterator m;
   for (m = FW.begin(); m != FW.end(); m++)
      cout << m->first << " = " << m->second << "\n";
}
int main(){
   string s = "Ajay Tutorial Plus, Ajay author";
   cout << "Total Number of Words=" << totalWords(s)<<endl;
   countFrequency(s);
   return 0;
}

Output

When the string “Ajay Tutorial Plus, Ajay author” supplied to this program, the total counts and frequencies of words in output as follows;

Enter a Total Number of Words=5
Ajay=2
Tutorial=1
Plus,=1
Author=1

Updated on: 23-Dec-2019

681 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements