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. Logic to search all occurrences of a word in given string.

Example

Input

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

Output

'love' is found at index: 2
'love' is found at index: 22 

Required knowledge

Basic C programming, Loop, String

Must know -

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

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

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

    strLen  = strlen(str);  // Find length of string
    wordLen = strlen(word); // Find length of word


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

        // If word have been found then print found message
        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 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>