String Exercises
Write a C program to remove all occurrences of a given word in string using loop. How to remove all occurrences of a word in given string using for loop in C programming. Deleting all occurrences of a word in given string in C program. Logic to remove all occurrences of a word in given string.
Required knowledge
Basic C programming, C if-else, C for loop, Array, functions, Strings
Logic to remove all occurrences 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.
- Run a loop from start of the string str to end.
- Inside loop, for each character in word match rest of characters with str. If all characters in word matched to str, then proceed to next step.
- If a word match is found then, shift all characters from current match position to left. Repeat step 4 till end of string str
Program to remove all occurrences of word
/** * C program to remove all occurrences of a word in given string */ #include#include #define MAX_SIZE 100 // Maximum string size /* Function declaration */ void removeAll(char * str, char * toRemove); int main() { char str[MAX_SIZE]; char toRemove[MAX_SIZE]; /* Input string and word from user */ printf("Enter any string: "); gets(str); printf("Enter word to remove: "); gets(toRemove); printf("String before removing '%s' : \n%s", toRemove, str); removeAll(str, toRemove); printf("\n\nString after removing '%s' : \n%s", toRemove, str); return 0; } /** * Remove all occurrences of a given word in string. */ void removeAll(char * str, char * toRemove) { int i, j, stringLen, toRemoveLen; int found; stringLen = strlen(str); // Length of string toRemoveLen = strlen(toRemove); // Length of word to remove for(i=0; i <= stringLen - toRemoveLen; i++) { /* Match word with string */ found = 1; for(j=0; j<toRemoveLen; j++) { if(str[i + j] != toRemove[j]) { found = 0; break; } } /* If it is not a word */ if(str[i + j] != ' ' && str[i + j] != '\t' && str[i + j] != '\n' && str[i + j] != '\0') { found = 0; } /* * If word is found then shift all characters to left * and decrement the string length */ if(found == 1) { for(j=i; j<=stringLen - toRemoveLen; j++) { str[j] = str[j + toRemoveLen]; } stringLen = stringLen - toRemoveLen; // We will match next occurrence of word from current index. i--; } } }