String Exercises
Write a C program to remove from last occurrence of a word in given string using loop. How to remove the last occurrence of any word in given string using loop in C programming. Logic to remove last occurrence of a word from given string.
Required knowledge
Basic C programming, C if-else, C for loop, Array, functions, Strings
Logic to remove last occurrence of a word
- 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, after loop if index != -1 then, word has been found. Hence, shift all characters to left from the current index position.
Program to remove last occurrence of a word
/** * C program to remove last occurrence of a word in given string */ #include <stdio.h> #include <string.h> #define MAX_SIZE 100 // Maximum string size int main() { char str[MAX_SIZE]; char word[MAX_SIZE]; int i, j, found, index; int stringLen, wordLen; /* Input string and word from user */ printf("Enter any string: "); gets(str); printf("Enter word to remove: "); gets(word); stringLen = strlen(str); // Length of string wordLen = strlen(word); // Length of word /* * Run loop from start to end of string - word length */ index = -1; for(i=0; i<stringLen - 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 is found then update index if(found == 1) { index = i; } } // If word not found if(index == -1) { printf("'%s' not found."); } else { /* * Shift all characters from right to left */ for(i=index; i <= stringLen - wordLen; i++) { str[i] = str[i + wordLen]; } printf("String after removing last '%s': \n%s", word, str); } return 0; }