C program to count occurrences of a word in a string

Write a C program to count occurrences of a word in a given string using loop. How to count total occurrences of a given word in a string using loop in C programming. Logic to count occurrences of a word in given string.

Example

Input

Input string: I love programming. I love Codeforwin.
Input word to search: love

Output

Total occurrences of 'love': 2

Required knowledge

Basic C programming, Loop, String, Function

Must know – Program to search all occurrences of a word in given string

Logic to count occurrences of a word in given string

Below is the step by step descriptive logic to count occurrences of a word in given string.

  1. Input string from user, store it in some variable say str.
  2. Input word to be searched from user, store it in some other variable say word.
  3. Initialize a counter variable to store total word match count i.e. say count = 0.
  4. Run a loop from start of the string str to end.
  5. Inside loop for each character in word match the rest of characters with str. If a word match is found in case increment count = count + 1.

Program to count occurrences of a word

/**
 * C program to count occurrences of a word in a given string
 */
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size

/* Function declaration */
int countOccurrences(char * str, char * toSearch);


int main()
{
    char str[MAX_SIZE];
    char toSearch[MAX_SIZE];
    int count;

    /* Input string and word from user */
    printf("Enter any string: ");
    gets(str);
    printf("Enter word to search occurrences: ");
    gets(toSearch);

    count = countOccurrences(str, toSearch);

    printf("Total occurrences of '%s': %d", toSearch, count);

    return 0;
}


/**
 * Get, total number of occurrences of a word in a string
 */
int countOccurrences(char * str, char * toSearch)
{
    int i, j, found, count;
    int stringLen, searchLen;

    stringLen = strlen(str);      // length of string
    searchLen = strlen(toSearch); // length of word to be searched

    count = 0;

    for(i=0; i <= stringLen-searchLen; i++)
    {
        /* Match word with string */
        found = 1;
        for(j=0; j<searchLen; j++)
        {
            if(str[i + j] != toSearch[j])
            {
                found = 0;
                break;
            }
        }

        if(found == 1)
        {
            count++;
        }
    }

    return count;
}

Output

Enter any string: I love programming. I love Codeforwin.
Enter word to search occurrences: love
Total occurrences of 'love': 2

Happy coding 😉