String Exercises
Write a C program to find last occurrence of a word in given string using loop. How to find last occurrence of a word in given string using loop in C programming. Logic to search last index of a word in given string in C programming.
Required knowledge
Basic C programming, C if-else, C for loop, Array, functions, Strings
Logic to search last occurrence of a word in string
Logic to search last occurrence of a word is almost similar to searching first occurrence of a word in string. Just with last occurrence of a word do not terminate loop if first occurrence is found.
Below is the step by step descriptive logic to search last occurrence of 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.
- Initialize a variable to store last matched index of word in given string, say index = -1. I have initially assumed that given word does not exists in string hence initialized with -1.
- Run a loop from start of the string str to end.
- Inside loop, for each character in word match the rest of characters with str. If all characters in word and str matches then, update index with current match position.
- Finally, check if(index == -1), then the given word does not exists in string.
Program to find last occurrence of word in string
/** * C program to find last occurrence of a word in given string */ #include#include #define MAX_SIZE 100 // Maximum string size int main() { char str[MAX_SIZE]; char word[MAX_SIZE]; int i, j, index, found; int strLen, wordLen; /* Input string and word from user */ printf("Enter any string: "); gets(str); printf("Enter any word to search: "); gets(word); index = -1; strLen = strlen(str); // Find length of string wordLen = strlen(word); // Find length of word /* * Runs a loop from starting index of string to * length of string - word length */ 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 word have been found then store the current found index if(found == 1) { index = i; } } if(index == -1) { printf("\n'%s' not found.", word); } else { printf("\nLast index of '%s' = %d", word, index); } return 0; }