Example:
Input string: I love programming!
Input word: love
Output: love is present at index 2.
Required knowledge
Basic C programming, Loop, StringProgram 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.
Enter word to be searched: love
'love' is found at index 2.
Happy coding ;)
You may also like
- String programming exercises index.
- C program to remove first occurrence of a character from the string.
- C program to convert uppercase string to lowercase string.
- C program to convert lowercase string to uppercase string
- C program to find frequency of each character in a string.
- C program to find first occurrence of a character in given string.
- C program to remove first occurrence of a character from the string.
- C program to remove last occurrence of a character from the string.
- C program to remove all occurrences of a character from the string.