Count Occurrences of a specific word in a string in C++

In this tutorial, we will learn how to count occurrences of a specific word in a given sentence in C++.

We are given a sentence containing the word we are to find, and we are supposed to return the count of that word in our given sentence.

Let us see how the algorithm works.

Algorithm to count occurrences of a word in a string

  1. Define a function WordOccurrence() containing two char pointer type arguments, namely sentence and word.
  2. We take two integers, slen and wordlen which store the value of the length of the sentence and word string respectively. strlen() function defined in the cstring header file was used to calculate the length of the strings.
  3. Another integer count is defined to store the count of the word and is initially assigned to zero.
  4. An integer i is used to run through the entire length of the sentence and another integer j is used to run through the length of the word we are trying to find in the given sentence. Nested for loop is used for this step. (If you wish you can check: How to break out of nested loops in C++ )
  5.  Then we check if sentence[i+j] is equal to word[j] or not. For example, initially we have i=0 and j=0, so we get sentence[0+0]=sentence[0]. If this is not equal to word[0], we break out of j’s for loop, or else we continue. This procedure is continued till j<wordlen.
  6. Finally, when j>=wordlen, j’s for loop is terminated and we get the final value of j.
  7. If this value of j is equal to the length of the word, we increment our count variable defined earlier.
  8. Finally, we return count.

Note: C++ is a case-sensitive language. Make sure to check for any ambiguity in the cases of the word to be found.

Sample input:
Sentence = hello world is the first program
Word = hello
Count = 1

C++ Code to Count Occurrences of a given word in a string

using namespace std;
int WordOccurrence(char *sentence, char *word)
    int slen = strlen(sentence);
    int wordlen = strlen(word);
    int count = 0;
    int i, j;
    for(i=0; i<slen; i++)
        for(j=0; j<wordlen; j++)
    return count;
int main()
    char word[] = "hello";
    char sentence[] = "hello world is the first hello program";
    cout<<"Number of ocurrences of word is: "<<WordOccurrence(sentence, word);
    return 0; 
Number of occurrences of the word is: 2

Leave a Reply

Your email address will not be published. Required fields are marked *