# C program to find the frequency of the given word in a string

Here, we are going to learn how to find the frequency of the given word in a string in C programming language?
Submitted by Nidhi, on July 18, 2021

Problem Solution:

Read a string and a word from the user, then find the frequency of the word in the string using C program.

Program:

The source code to find the frequency of the given word in a string is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

```// C program to find the frequency of given word in a string

#include <stdio.h>
#include <string.h>

int FindFrequency(char* str, char* word)
{
int len = 0;
int wlen = 0;
int cnt = 0;
int flg = 0;

int i = 0;
int j = 0;

len = strlen(str);
wlen = strlen(word);

for (i = 0; i <= len - wlen; i++) {

flg = 1;
for (j = 0; j < wlen; j++) {
if (str[i + j] != word[j]) {
flg = 0;
break;
}
}

if (flg == 1)
cnt++;
}

return cnt;
}

int main()
{
char str;
char word;

int count = 0;

printf("Enter string: ");
scanf("%[^\n]s", str);

printf("Enter word to be searched: ");
scanf("%s", word);

count = FindFrequency(str, word);

printf("Frequency of the word '%s' is: %d\n", word, count);

return 0;
}
```

Output:

```RUN 1:
Enter string: Hello freiends, say Hello
Enter word to be searched: Hello
Frequency of the word 'Hello' is: 2

RUN 2:
Enter string: This is india
Enter word to be searched: is
Frequency of the word 'is' is: 2
```

Explanation:

In the above program, we created two functions FindFrequency() and main(). The FindFrequency() is used to count the occurrences of the specified word in the specified string.

In the main() function, we read the value of string str and word word from the user. Then we called FindFrequency() function to find the frequency of the word and printed the result on the console screen.