Example:
Input string: I am a programmer. I love CodeforWin
Input word to remove: I
Output: I am a programmer. love CodeforWin
Required knowledge
Basic C programming, Loop, StringBefore moving on to this program you must be done with two programs - C program to remove last occurrence of a character and C program to find last occurrence of word in given string. As logic of this program is based on these two programs.
Program to remove last occurrence of word
/** * C program to remove 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, index; 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 */ index = -1; 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) { index = i; } } //If word not found if(index == -1) { printf("'%s' not found.\n"); } else { /* * Shifts all characters from right to left */ for(i=index; i<stringLen - wordLen; i++) { string[i] = string[i + wordLen]; } //Makes last character null. string[i] = '\0'; printf("String after removing last '%s': %s\n", word, string); } return 0; }
Output
Enter any string: I love programming. I love CodeforWin.
Enter any word to search: I
String after removing last 'I': I love programming. love CodeforWin.
Enter any word to search: I
String after removing last 'I': I love programming. love CodeforWin.
Happy coding ;)
You may also like
- String programming exercises index.
- C program to find first occurrence of a word in given string.
- C program to search all occurrences of a word in given string.
- C program to remove first occurrence of a word in given string.
- C program to find first occurrence of a character in given string.
- C program to find last occurrence of a character in given string.
- C program to search all occurrence of a character in given string.
- C program to remove first occurrence of a character in given string.
- C program to remove last occurrence of a character in given string.
- C program to remove all occurrences of a character in given string.
- C program to count occurrences of a character in given string.
- C program to count frequency of each character in given string.