Count occurrences of a word in string



Count occurrences of a word in string

You are given a string and a word your task is that count the number of the occurrence of the given word in the string and print the number of occurrences of the word.
Examples:

Input : string = "GeeksforGeeks A computer science portal for geeks"
word = "portal"
Output : Occurrences of Word = 1 Time

Input : string = "GeeksforGeeks A computer science portal for geeks"
word = "technical" 
Output : Occurrences of Word = 0 Time

Approach:

  • First, we split the string by spaces in a
  • Then, take a variable count = 0 and in every true condition we increment the count by 1
  • Now run a loop at 0 to length of string and check if our string is equal to the word
  • if condition is true then we increment the value of count by 1 and in the end, we print the value of count.

Below is the implementation of the above approach :

// C++ program to count the number
// of occurrence of a word in
// the given string
#include <bits/stdc++.h>
using namespace std;
int countOccurrences(char *str,
                    string word)
{
    char *p;
    // split the string by spaces in a
    vector<string> a;
    p = strtok(str, " ");
    while (p != NULL)
    {
        a.push_back(p);
        p = strtok(NULL, " ");
    }
    // search for pattern in a
    int c = 0;
    for (int i = 0; i < a.size(); i++)
        // if match found increase count
        if (word == a[i])
            c++;
    return c;
}
// Driver code
int main()
{
    char str[] = "GeeksforGeeks A computer science portal for geeks ";
    string word = "portal";
    cout << countOccurrences(str, word);
    return 0;
}
// This code is contributed by
// sanjeev2552

Output:

1

Last Updated on October 28, 2021 by admin

Leave a Reply

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

Recommended Blogs