C Program to Count Occurrence of Word in String

Write C Program to Count Occurrence of Word in String

// C Program to Count Occurrence of Word in String

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
	char S1[50], S2[50];
	int index, i, l1, l2, j , max, count = 0, flag = 0;

	printf("Enter String :--> ");
	gets(S1);

	printf("Enter Word to Search:--> ");
	gets(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)
		printf("Word Appears %d Times",count);
	else
		printf("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

≪ Previous | Next ≫