Introduction:
In this tutorial we will find the frequency of each word in a given sentence. so let's understand the problem first.
Problem Statement:
we have given a sentence:"my name is chris and chris is smart";
then we have to check how much time each word is appeared in the sentence. in the above given sentence:
freq of "my" = 1;
freq of "name" = 1;
freq of "is" = 2;
freq of "chris" = 2;
freq of "and" = 1;
freq of "smart" = 1;
Solution:
so if you think little, then you can see that to solve this problem we have to do two thing:
first find the word and then increase the count of that word. so if there is a need to find something then we should go with hashmap.
let's solve it using hashmap:
code:
#include<bits/stdc++.h>
using namespace std;
int main(){
string sentence;
getline(cin, sentence); // we use getline for sentence
map<string,int>m;
for(int i=0;i<sentence.size();i++){
if(m.find(sentence[i])!=m.end()){
auto it = m.find(sentence[i]);//find the word
it->second++;//increase the count
}
m.insert(make_pair(sentence[i],1);//not already in the map, then put into map and make it's count=1
}
for(auto it = m.begin(); it!=m.end();it++){
cout<<it->first<<":"<<it->second<<endl;
}
}
for better understanding see the image below:
Comments
Post a Comment