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. Program to count total number of occurrences of a given string in another string in C.

Example:
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

Before counting total occurrences of a given word in a string you must know the basics of how to count total occurrences of a character in given string.

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 size of string


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



int main()
{
    char string[MAX_SIZE];
    char toSearch[MAX_SIZE];
    int occurrences;

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

    occurrences = countOccurrences(string, toSearch);

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

    return 0;
}




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

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

    occurrences = 0;

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

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

    return occurrences;
}


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

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment