Search all occurrences of a word in a given string with C.
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
char word[100];
int i, j, found;
int strLen, wordLen;
/* Input string and word from user */
printf("Enter any string: ");
gets(str);
printf("Enter any word to search: ");
gets(word);
strLen = strlen(str); // Find length of string
wordLen = strlen(word); // Find length of word
for (i = 0; i < strLen - wordLen; i++)
{
// Match word at current position
found = 1;
for (j = 0; j < wordLen; j++)
{
// If word is not matched
if (str[i + j] != word[j])
{
found = 0;
break;
}
}
if (found == 1)
{
printf("'%s' found at index: %d \n", word, i);
}
}
return 0;
}
Output
Enter any string : I love Coding.I love Bangladesh
Enter any word to search : love
'love' found at index : 2
'love' found at index : 16
0 Comments