Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements