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.
- Input string from user, store it in some variable say str.
- Input word to be searched from user, store it in some other variable say word.
- Run a loop from start of the string str to end.
- 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.
- 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 😉
Recommended posts
- String programming exercises index.
- C program to search all occurrences of a word in given string.
- C program to count occurrences of a word in given string.
- C program to remove first occurrence of word with another in given string.
- C program to remove last occurrence of a word with another in given string.
- C program to remove all occurrences of a word with another in given string.
- C program to remove first occurrence of a character from given string.
- C program to replace first occurrence of a character from given string.