0

Given an array of words and a string, I need to count all the words that are present in a given string.

I have split the sentence and included the words in a hash map. However, when I iterate through the string array to check if that word is present, I'm getting an incorrect output. How do I rectify the code?

#include<bits/stdc++.h> 
using namespace std; 
void countwords(string str,string words[],int n )
{
    map<string ,bool > m1;  //map 
    map<string ,bool > ::iterator it; 
    int i=0,cnt=0; 
    string temp = " "; 
    while(i<str.size()) // splitting of sentence into words
    {
        while(str[i]!=' '&&i<str.size()&&str[i]!='.') // if it doesnt encounter space, add it to temp
        {
            temp+=str[i]; 
            i++; 
        }
        m1[temp]=true;  // insert temp into map
        temp=" "; 
        i++; 
    }

    for(i=0;i<n;i++)
    { 
        if(m1.find(words[i])!=m1.end()&&m1[words[i]]==true) // if word is present in the map increment count & it isn't a duplicate
        {    
            cnt++; 
            m1[words[i]]=false;
         } 
     } 
     cout<<cnt; 
}
theduck
  • 2,589
  • 13
  • 17
  • 23
bunny bugs
  • 35
  • 7

1 Answers1

1

There are some problems with your code.

1- temp = " " , you need to set temp to an empty string or the find() function will not work for it

2- using map, you will have only one instance of a word in map, so you need to keep a count of each word.

Below code counts and prints number of words of a given array, with minimum changes to your code:

void countwords(string str,string words[],int n ){
map<string ,int > m1;
int i=0, cnt=0;
string temp = "";
while(i < str.size())
{
    while(str[i]!=' ' && i<str.size() && str[i]!='.')
    {
        if(str[i]!=' ' && str[i]!='.')
            temp+=str[i];
        i++;
    }
    auto iii = m1.find(temp);
    int count = 0;
    if(iii != m1.end())
        count = iii->second;
    count+=1;
    m1[temp]=count;

    temp="";
    i++;
}

for(int i=0; i != n; i++)
{
    auto found = m1.find(words[i]);
    if(found != m1.end())
        std::cout << found->first << " " << found->second << std::endl;
    else cout << words[i] << " " << "0" << std::endl;
}}
Roya Ghasemzadeh
  • 673
  • 5
  • 16