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

1 Answer

0 votes
#include <iostream>
#include <string>
#include <sstream>
 
int countOccurrences(const std::string& s, const std::string& word) {
    std::istringstream stream(s);
    std::string token;
    int count = 0;
     
    while (stream >> token) {
        if (token == word) {
            count++;
        }
    }
     
    return count;
}
 
int main() {
    std::string s = "c++ c python php c++ c++ php php kotlin c# c++";
    std::string word = "c++";
     
    std::cout << "Occurrences of '" << word << "': " << countOccurrences(s, word) << std::endl;
}
 
 
/*
run:
 
Occurrences of 'c++': 4
 
*/

 



answered Jan 24, 2021 by avibootz
edited Mar 1, 2025 by avibootz

Related questions

1 answer 282 views
1 answer 351 views
1 answer 227 views
3 answers 290 views
3 answers 296 views
1 answer 256 views
1 answer 208 views
...