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