Write a program that replaces all occurrences of a string STR1 with the string STR2 in a string STR. Use a END to save the string during the replacement.
Examples:
- replacing all occurrences of 'PHON' by 'OY' in 'ALPHONSE' gives 'ALOYSE'
- replacing all occurrences of 'AN' by 'ONT' in 'BANANE' gives 'BONTONTE'
- replacing all occurrences of 'T' by 'Y' in 'TOTALEMENT' gives 'YOYALEMENY'
- replacing all occurrences of '' by 'TTT' in 'HELLO' gives 'HELLO'
- replacing all occurrences of 'L' by '' in 'HELLO' gives 'HEO'
Difficulty level
![](images/star4.png)
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 STR1[100]; /* string to find */
char STR2[100]; /* replacement string */
char END[100]; /* string to display */
int I; /* counter for STR */
int J; /* counter for STR1 and STR2 */
int K; /* counter for copy */
/* 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 */
for (I = 0; STR[I]; I++)
if (STR[I] == STR1[0])
{
for (J = 1; STR1[J] && (STR1[J] == STR[I + J]); J++)
;
if (STR1[J] == '\0') /* FOUND ! */
{
/* 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 and move */
/* I behind the copy of STR2. */
for (K = 0; STR2[K]; K++, I++)
STR[I] = STR2[K];
/* Recopy END to STR */
for (K = 0; END[K]; K++)
STR[I + K] = END[K];
/* Terminate the STR string */
STR[I + K] = '\0';
I--; /* readjust the I counter */
}
}
/* display */
printf("Resulting string : \"%s\"\n", STR);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
![](images/star5.png)