Example:
Input string: I love programming. I love CodeforWin.
Input word: love
Output 'love' is found at index: 2,
Required knowledge
Basic C programming, Loop, StringBefore moving on to this program you must know how to find first occurrence of a word and last occurrence of a word in given string.
Program to search occurrences of a word in string
/** * C program to find last occurrence of a word in given string */ #include <stdio.h> #include <string.h> #define MAX_SIZE 100 //Maximum size of string int main() { char string[MAX_SIZE]; char word[MAX_SIZE]; int i, j, found; int stringLen, wordLen; /* * Reads string and word from user */ printf("Enter any string: "); gets(string); printf("Enter any word to search: "); gets(word); stringLen = strlen(string); //Finds length of string wordLen = strlen(word); //Finds length of word /* * Runs a loop from starting index of string to * length of string - word length */ for(i=0; i<stringLen - wordLen; i++) { //Matches the word at current position found = 1; for(j=0; j<wordLen; j++) { //If word is not matched if(string[i+j] != word[j]) { found = 0; break; } } //If word have been found then store the current found index if(found == 1) { printf("'%s' found at index: %d\n ", word, i); } } return 0; }
Output
Enter any string: I love programming. I love CodeforWin. I love computers.
Enter any word to search: love
'love' found at index: 2
'love' found at index: 22
'love' found at index: 41
Enter any word to search: love
'love' found at index: 2
'love' found at index: 22
'love' found at index: 41
Happy coding ;)
You may also like
- String programming exercises index.
- C program to find first occurrences of a character in given string.
- C program to find last occurrences of a character in given string.
- C program to search all occurrences of a character in given string.
- C program to remove first occurrences of a character in given string.
- C program to remove last occurrences of a character in given string.
- C program to remove all occurrences of a character in given string.
- C program to count frequency of each character in given string.
- C program to remove first occurrences of a word in given string.
- C program to check palindrome string using loop.