Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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[64];
    char word[16];

    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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now