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,884 questions

51,810 answers

573 users

How to count the occurrences of each word in a string with C++

1 Answer

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

std::map<std::string, int> countOccurrences(std::string s) {
    int count = 1;
    std::map<std::string, int> mp;
    std::istringstream iss(s);
    std::string word;
      
    while (iss >> word) {
        std::pair<std::map<std::string, int>::iterator, bool> pr;

        pr = mp.insert(std::pair<std::string, int>(word, count));

        if (pr.second==false) {
            pr.first->second++; 
        }     
    }
       
    return mp;
}

int main() {
    std::string s = "c python c++ java c c++ php c++ c c java";

    std::map<std::string, int> mp = countOccurrences(s);
    
    std::map<std::string,int>::iterator itr ;

    for (itr = mp.begin(); itr != mp.end(); itr++) {
        std::cout << itr->first << " - " << itr->second << '\n';
    }
    
    return 0;
}
 
 
 
  
/*
run:
  
c - 4
c++ - 3
java - 2
php - 1
python - 1
 
*/

 



answered Jan 24, 2021 by avibootz

Related questions

1 answer 224 views
1 answer 166 views
1 answer 82 views
1 answer 97 views
1 answer 85 views
1 answer 92 views
...