Signup/Sign In
PUBLISHED ON: FEBRUARY 8, 2022

C Program To Remove Given Word From A String

Learn C language tutorial

Logic:

  • Get the input from the user and store it in the main array,
  • Get another input from the user and store it in the subarray,
  • Here the inputs are stored as a 2d array, after getting the second input from the user,
  • the strcmp(), the function is used to compare the entered word and the word in the sentence,
  • Search for the given word in the 2d array, Once the given word is found the next line will be printed on it.

C Language Program To Remove Given Word From A String:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main ()
{
	char str[50], str1[50], td[20][30];
	int i = 0, j = 0, k = 0, x = 0, y = 0;
 
	printf ("Enter The Main String:\n");
	gets (str);
 
	printf ("Enter A Word To Be Removed From The Main String:\n");
	gets (str1);
	for (i = 0; str[i] != '\0'; i++)
	{
		if (str[i] == ' ')
		{
			td[k][j] = '\0';
			k ++;
			j = 0;
		}
		else
		{
			td[k][j] = str[i];
			j ++;
		}
	}
 
	td[k][j] = '\0';
 
	j = 0;
	for (i = 0; i < k + 1; i++)
	{
		if (strcmp(td[i], str1) == 0)
		{
			td[i][j] = '\0';
		}
	}
 
	j = 0;
 
	for (i = 0; i < k + 1; i++)
	{
		if (td[i][j] == '\0')
			continue;
		else
			printf ("%s ", td[i]);
	}
 
	printf ("\n");
 
	return 0;
}

Output:

Remove



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight