C Programming Code Examples C > Strings Code Examples C program to remove all occurrences of a word in string C program to remove all occurrences of a word in string 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. 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 #include <stdio.h> #include <string.h> #define maxsize 100 // Maximum string size /* Function declaration */ void removeAll(char * str, char * toRemove); int main() { char str[maxsize]; char toRemove[maxsize]; /* 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 x, j, stringLen, toRemoveLen; int found; stringLen = strlen(str); // Length of string toRemoveLen = strlen(toRemove); // Length of word to remove for(x=0; x <= stringLen - toRemoveLen; x++) { /* Match word with string */ found = 1; for(j=0; j<toRemoveLen; j++) { if(str[x + j] != toRemove[j]) { found = 0; break; } } /* If it is not a word */ if(str[x + j] != ' ' && str[x + j] != '\t' && str[x + j] != '\n' && str[x + j] != '\0') { found = 0; } /* If word is found then shift all characters to left and decrement the string length */ if(found == 1) { for(j=x; j<=stringLen - toRemoveLen; j++) { str[j] = str[j + toRemoveLen]; } stringLen = stringLen - toRemoveLen; // We will match next occurrence of word from current index. x--; } } }