c++ count the number of occurrences of a word in string code example

Example 1: find all occurrences of a substring in a string c++

#include <string>
#include <iostream>

using namespace std;

int main()
{
    string s("hello hello");
    int count = 0;
    size_t nPos = s.find("hello", 0); // first occurrence
    while(nPos != string::npos)
    {
        count++;
        nPos = s.find("hello", nPos + 1);
    }

    cout << count;
};

Example 2: string count occurrences c++

#include <algorithm>

std::string s = "a_b_c";
size_t n = std::count(s.begin(), s.end(), '_'); //n=2

Example 3: count occurrences of character in string c++

std::string s = "a_b_c";
size_t n = std::count(s.begin(), s.end(), '_'); // n=2

Example 4: check how many of a word is in a string

function countOccurences(str,word)  
{ 
    // split the string by spaces in a 
    String a[] = str.split(","); 
  
    // search for pattern in a 
    int count = 0; 
    for (int i = 0; i < a.length; i++)  
    { 
    // if match found increase count 
    if (word.equals(a[i])) 
        count++; 
    } 
  
    return count; 
}

Example 5: Write a c++ program that reads a sentence (including spaces) and a word, then print out the number of occurrences of the word in the sentence

Write a c++ program that reads a sentence (including spaces) and a word, then print out the number of occurrences of the word in the sentence