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. How to check whether a string exists in a given string.

Example:
Input string: I love programming!
Input word: love
Output: love is present at index 2.

Required knowledge

Basic C programming, Loop, String

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

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

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


    /* Searches in the string word by word */
    index = 0;
    while(string[index] != '\0')
    {

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

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

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

    return 0;
} 


Output
Enter any string: I love programming.
Enter word to be searched: love
'love' is found at index 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