How to count only the unique words from a string in C++

1 Answer

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

int countUniqueWords(std::string str) {
    std::stringstream iss(str);
    std::unordered_map<std::string, unsigned> map;
     
    std::string word;  
    while (iss >> word) {
        map[word]++;
    }
    
    return map.size();
}

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

    std::cout << countUniqueWords(s);
    
    return 0;
}





/*
run:

6

*/

 



answered Feb 10, 2022 by avibootz

Related questions

1 answer 115 views
1 answer 115 views
1 answer 119 views
1 answer 113 views
1 answer 115 views
1 answer 153 views
1 answer 134 views
...