Write a program that replaces the first occurrence of a string STR1 with the string STR 2 in a string STR. Use an END string to save the string during the replacement.

Examples:

  • replacing the first occurrence of 'PHON' by 'OY' in 'ALPHONSE' gives 'ALOYSE'
  • replacing the first occurrence of 'IE' by 'EI' in 'PIERRE' gives 'PEIRRE'
  • replacing the first occurrence of 'IE' by 'ARTE' in 'PIERRE' gives 'PARTERRE'
  • replacing the first occurrence of 'EI' by 'IE' in 'PIERRE' gives 'PIERRE'
  • replacing the first occurrence of 'TOT' by 'FIN' in 'TOTALLY' gives 'FINALLY'
  • replacing the first occurrence of '' by 'TTT' in 'HELLO' gives 'HELLO'

Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
void main()
{
	/* Drclarations */
	char STR[100]; /* string to transform */
	char STR1[100]; /* string to find  */
	char STR2[100]; /* replacement string */
	char END[100]; /* resulting string */
	int I;      /* counter in STR */
	int J;      /* cunter in STR1 and STR2 */
	int K;      /* counter for copying  */
	int FOUND; /* flag indicating indicating whether STR1 is founnd */

	/* Read */
	printf("Enter the string to find STR1      : ");
	gets(STR1);
	printf("Enter the replacement string STR2  : ");
	gets(STR2);
	printf("Enter the  string to transform STR : ");
	gets(STR);

	/* find STR1 in STR */
	FOUND = 0;
	for (I = 0; STR[I] && !FOUND; I++)
		if (STR[I] == STR1[0])
		{
			for (J = 1; STR1[J] && (STR1[J] == STR[I + J]); J++)
				;
			if (STR1[J] == '\0') FOUND = 1;
		}


	/* If STR1 was found in STR then save the end of STR */
	/* in END, then copy STR2 and END to STR.   */
	if (FOUND)
	{
		I--;
		/* Now I indicates the position of STR1 */
		/* in STR and J indicates the length of STR1 */
		/* Save the end of STR in END */
		for (K = 0; STR[K + I + J]; K++)
			END[K] = STR[K + I + J];
		END[K] = '\0';

		/* Copy STR2 to STR */
		for (K = 0; STR2[K]; K++, I++)
			STR[I] = STR2[K];

		/* Copy END to STR */
		for (K = 0; END[K]; K++, I++)
			STR[I] = END[K];
		/* Terminate the STR string */
		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 !!
Find efficiently the minimum element in a stack without using an auxiliary stack