Write a program that deletes the first occurrence of an DEL string in a STR string.

Examples:

  • deleting the first occurrence of 'PHON' from 'ALPHONSE gives 'ALSE'
  • deleting the first occurrence of 'EI' from 'PIERRE gives 'PIERRE'
  • deleting the first occurrence of 'T' from 'TOTALLLY' gives 'OTALLLY'
  • deleting the first occurrence of ''from 'HELLO' gives 'HELLO'

Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
void main()
{
	/* Declarations */
	char STR[100]; /* String to transform           */
	char DEL[100]; /* string to be deleted from STR */
	int I;         /* counter in STR                */
	int J;         /* counter in DEL                */
	int FOUND ;    /* flag indicating if  */
				   /* DEL is found in STR */

	/* reding */
	printf("Enter the string to be deleted : ");
	gets(DEL);
	printf("Enter the string to transform  : ");
	gets(STR);
	/* find DEL in STR */
	FOUND = 0;
	for (I = 0; STR[I] && !FOUND; I++)
		/* If the first letter is identical, */
		if (STR[I] == DEL[0])
		{
			/* then compare the rest of the string */
			for (J = 1; DEL[J] && (DEL[J] == STR[I + J]); J++)
				;
			if (DEL[J] == '\0') FOUND = 1;
		}
	/* If the starting position of DEL is found in STR */
	/* then move the rest of STR to this position. */
	if (FOUND)
	{
		I--;
		/* Now I indicates the position of DEL */
		/* in STR and J indicates the length of DEL */
		for (; STR[I + J]; I++)
			STR[I] = STR[I + J];
		STR[I] = '\0';
	}
	/* Display */
	printf("Resulting string : \"%s\"\n", STR);
	getch();
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Reverse level order