C Programming Code Examples C > Strings Code Examples program to find last occurrence of a word in given string program to find last occurrence of a word in given string 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 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. 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. #include <stdio.h> #include <string.h> #define maxsize 100 // Maximum string size int main() { char str[maxsize]; char word[maxsize]; int x, 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(x=0; x<=strLen - wordLen; x++) { // Match word at current position found = 1; for(j=0; j<wordLen; j++) { //If word is not matched if(str[x + j] != word[j]) { found = 0; break; } } // If word have been found then store the current found index if(found == 1) { index = x; } } if(index == -1) { printf("\n'%s' not found.", word); } else { printf("\nLast index of '%s' = %d", word, index); } return 0; }