Answer to Question #333267 in C++ for Program Training

Question #333267

Define a function named GetWordFrequency that takes a vector of strings and a search word as parameters. Function GetWordFrequency() then returns the number of occurrences of the search word in the vector parameter (case insensitive). 

Then, write a main program that reads a list of words into a vector, calls function GetWordFrequency() repeatedly, and outputs the words in the vector with their frequencies. The input begins with an integer indicating the number of words that follow. 

Ex: If the input is:

5 hey Hi Mark hi mark

the output is:

hey 1
Hi 2
Mark 2
hi 2
mark 2
1
Expert's answer
2022-04-24T17:15:51-0400



#include <iostream>
#include <vector>
#include <iomanip>
#include <string.h>
#include <string>
#include <algorithm>//USE C++14
using namespace std;
bool stringiEq(const string& a, const string& b)
{
  //check each characters by case insensitive  
  return std::equal(a.begin(), a.end(),
                      b.begin(), b.end(),
                      [](char a, char b) {
                          return tolower(a) == tolower(b);
                      });
}
unsigned GetWordFrequency(vector<string>&vs,const string&str)
{
  //return the number of occurrences of the search word in the 
  //vector parameter (case insensitive). 
  unsigned ans=0;//the numbers of occurences 
  for(auto it:vs)
    {
      if(stringiEq(it,str))
        ans++;
    }
  return ans;
}
int main()
{
  int size=0;
  cin>>size;
  vector<string>vs;
  for(int i=0;i<size;i++)
    {
      string s;
      cin>>s;
      vs.push_back(s);
    }
  for(auto it:vs)
    {
      cout<<setw(20)<<it<<" -> "<<GetWordFrequency(vs,it)<<endl;
    }
  cout<<"----------------END-----------------\n";
  return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS