Write a C program to read a string from user and find the first occurrence of word in a given string. How to find the first occurrence of a word in a given string in C. 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 3.
Happy coding ;)
Example:
Input string: I love programming.
Input word: love
Output: love is present at 3.
Required knowledge
Basic C programming, Loop, StringProgram
/**
* C program to find the first occurrence of a word in a string
*/
#include <stdio.h>
#include <string.h>
int main()
{
char text[100], word[20];
int pos, i, found = 0;
/*
* Reads a string from user and word to be searched
*/
printf("Enter any string: ");
gets(text);
printf("Enter character to be searched: ");
gets(word);
/*
* Searches in the string word by word
*/
pos = 0;
while(text[pos] != '\0')
{
/*
* If first character matches with the given string
*/
if(text[pos]==word[0])
{
/*
* Match entire word with current found index
*/
i=0;
found = 1;
while(word[i]!='\0')
{
if(text[pos+i] != word[i])
{
found = 0;
break;
}
i++;
}
}
/* If the word is found then get out of loop */
if(found == 1)
{
break;
}
pos++;
}
/*
* If the word is found print success message
*/
if(found == 1)
{
printf("\"%s\" is found in string \"%s\" at %d position.", word, text, (pos+1));
}
else
{
printf("\"%s\" is not found in string \"%s\"", word, text);
}
return 0;
}
Output
Enter any string: I love programming.
Enter character to be searched: love
"love" is found in string "I love programming." at 3 position.
Enter character to be searched: love
"love" is found in string "I love programming." at 3 position.
Happy coding ;)
You may also like
- String programming exercises and solution.
- C program to remove first occurrence of a character from the string.
- C program to find length of a string.
- C program to copy one string to another string.
- C program to concatenate two strings.
- C program to compare two different strings.
- C program to convert uppercase string to lowercase string.
- C program to convert lowercase string to uppercase string
- C program to find reverse of a given string.
- C program to check whether a string is palindrome or not.
- C program to count total number of alphabets, digits and special characters in a string.
- C program to count number of vowels and consonants in a string.
- C program to find total number of words in a 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.