C program to find first occurrence of a word in a string

Write a C program to find the first occurrence of word in a string using loop. How to find the first occurrence of any word in a given string in C programming. Logic to search a word in a given string in C programming.

Example

Input

Input string: I love programming!
Input word to search: love

Output

'love' is found at index 2.

Required knowledge

Basic C programming, Loop, String

Read more – Program to find first occurrence of a character

Logic to find first occurrence of a word

Below is the step by step descriptive logic to search 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. Run a loop from start of the string str to end.
  4. Inside loop for each character in string str. Match first character of word with current character of str. If both matched then proceed to below step otherwise continue to next character in str.
  5. If current character of str is equal to first character of word. Then, for each character in word match the rest of characters with str. If any character does not matches then go back to step 4.

Program to find first occurrence of a word

/**
 * C program to find the first occurrence of a word in a string
 */
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
    char str[MAX_SIZE], word[MAX_SIZE];
    int i, index, found = 0;

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


    /* Run loop from start to end of string */
    index = 0;
    while(str[index] != '\0')
    {

        /* If first character of word matches with the given string */
        if(str[index] == word[0])
        {
            /* Match entire word with current found index */
            i=0;
            found = 1;
            while(word[i] != '\0')
            {
                if(str[index + i] != word[i])
                {
                    found = 0;
                    break;
                }

                i++;
            }
        }
        
        /* If the word is found then get out of loop */
        if(found == 1)
        {
            break;
        }

        index++;
    }
    
    /*  Print success message if the word is found */
    if(found == 1)
    {
        printf("\n'%s' is found at index %d.", word, index);
    }
    else
    {
        printf("\n'%s' is not found.", word);
    }

    return 0;
}

Read more – Program to find last occurrence of a word in given string

Output

Enter any string: I love programming.
Enter word to be searched: love

'love' is found at index 2.

Happy coding 😉