C++ Program to Count Occurrence of Word in String
Write C++ Program to Count Occurrence of Word in String
// CPP Program to Count Occurrence of Word in String
#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
int main()
{
char S1[50], S2[50];
int index, i, l1, l2, j , Max, Count = 0, flag = 0;
cout << "Enter String :--> ";
gets(S1);
cout << "Enter Word to Search:--> ";
cin >> S2;
l1 = strlen(S1);
l2 = strlen(S2);
Max = l1 - l2;
for(i = 0;i <= Max; i++)
{
if(strncmp(S1 + i, S2, l2) == 0)
/* here a and b is considered as array address and a+i means array is
compared with array b up to the size of substring */
Count++;
}
if(Count != 0)
cout << "Word Appears " << Count <<" Times";
else
cout << "Word Not Found";
return 0;
}
Output:
Run 1:
Enter String :--> The essens of the programing is the short code
Enter Word to Search:--> the
The Word Appears 2 Times
Run 2:
Enter String :--> The essens of the programing is the short code
Enter Word to Search:--> CODE
Word Not Found