C program to search all occurrences of a word in given string

Write a C program to search all occurrences of a word in given string using loop. How to find index of all occurrences of a word in given string using loop in C programming. Program to print index of all occurrence of given word in string.

Example:
Input string: I love programming. I love CodeforWin.
Input word: love
Output 'love' is found at index: 2,

Required knowledge

Basic C programming, Loop, String

Before moving on to this program you must know how to find first occurrence of a word and last occurrence of a word in given string.

Program to search occurrences of a word in string

/**
 * C program to find last occurrence of a word in given string
 */

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 //Maximum size of string

int main()
{
    char string[MAX_SIZE];
    char word[MAX_SIZE];
    int i, j, found;
    int stringLen, wordLen;

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

    stringLen = strlen(string); //Finds length of string
    wordLen = strlen(word); //Finds length of word


    /*
     * Runs a loop from starting index of string to
     * length of string - word length
     */
    for(i=0; i<stringLen - wordLen; i++)
    {
        //Matches the word at current position
        found = 1;
        for(j=0; j<wordLen; j++)
        {
            //If word is not matched
            if(string[i+j] != word[j])
            {
                found = 0;
                break;
            }
        }

        //If word have been found then store the current found index
        if(found == 1)
        {
            printf("'%s' found at index: %d\n ", word, i);
        }
    }

    return 0;
}


Output
Enter any string: I love programming. I love CodeforWin. I love computers.
Enter any word to search: love
'love' found at index: 2
'love' found at index: 22
'love' found at index: 41

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