Quantcast
Channel: Codeforwin
Viewing all articles
Browse latest Browse all 132

C program to remove all occurrences of a word in string

$
0
0
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.

Example:
Input string: I love programming. I love CodeforWin.
Input word to remove: I
Output after deleting 'I': love programming. love CodeforWin.

Required knowledge

Basic C programming, Loop, String

Before moving on to this program you must first know how to remove first occurrence of a word, last occurrence of a word and remove all occurrences of a character in given string.

Program to remove all occurrences of word


/**
* C program to remove all occurrences of a word in given string
*/

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100 //Maximum size of string


/* Function declaration */
void removeAll(char * string, char * toRemove);



int main()
{
char string[MAX_SIZE];
char toRemove[MAX_SIZE];

/*
* Reads string and word from user
*/
printf("Enter any string: ");
gets(string);
printf("Enter word to remove: ");
gets(toRemove);

printf("String before removing '%s' : %s\n", toRemove, string);

removeAll(string, toRemove);

printf("String after removing '%s' : %s\n", toRemove, string);

return 0;
}



/**
* Removes all occurrences of a given word in string.
*/
void removeAll(char * string, char * toRemove)
{
int i, j, stringLen, toRemoveLen;
int found;

stringLen = strlen(string); //Gets length of string
toRemoveLen = strlen(toRemove); //Gets length of word to remove


for(i=0; i<stringLen - toRemoveLen; i++)
{
/*
* Matches word with the string
*/
found = 1;
for(j=0; j<toRemoveLen; j++)
{
if(string[i + j] != toRemove[j])
{
found = 0;
break;
}
}


/*
* 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++)
{
string[j] = string[j + toRemoveLen];
}
string[j] = '\0';

stringLen = stringLen - toRemoveLen;
}
}
}


Output
Enter any string: I love programming. I love CodeforWin.
Enter word to remove: I
String before removing 'I' : I love programming. I love CodeforWin.
String after removing 'I' : love programming. love CodeforWin.

Happy coding ;)



Viewing all articles
Browse latest Browse all 132

Trending Articles