Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,948 questions

51,890 answers

573 users

How to find the number of occurrences (frequency) of each word in a string in C++

1 Answer

0 votes
#include <iostream>
#include <map>

std::map<std::string, int> getOccurrences(std::string s) {
    std::map<std::string, int> mp;
 
    std::string word = "";
 
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == ' ') {
            if (mp.find(word) == mp.end()) {
                mp.insert(make_pair(word, 1));
                word = "";
            }
 
            else {
                mp[word]++;
                word = "";
            }
        }
 
        else
            word += s[i];
    }
 
    if (mp.find(word) == mp.end()) {
        mp.insert(make_pair(word, 1));

    }
    else
        mp[word]++;

    return mp;
}
 
int main()
{
    std::string s = "c++ php c java c++ python c# c c java";
 
    std::map<std::string, int> mp = getOccurrences(s);
    
    for (auto& it : mp) {
        std::cout << it.first << " - " << it.second << "\n";
    }
    
    return 0;
}




/*
run:

c - 3
c# - 1
c++ - 2
java - 2
php - 1
python - 1

*/

 



answered Jan 19, 2021 by avibootz
...