CPP Program Replace Character Recursively – Advanced Recursion

Given an input string S and two characters c1 and c2, you need to replace every occurrence of character c1 with character c2 in the given string. Do this recursively.

Input format:

Line 1: Input String S
Line 2: Characters c1 and c2 (separated by space)

Output format:

Updated string

Constraints:

1 <= Length of String S <= 10^6

Sample Input:

abacd
a x

Sample Output:

xbxcd 

Code:

void replaceCharacter(char s[], char c1, char c2)
{
    if(s[0]=='\0') return;
    
    if(s[0]==c1) s[0]=c2;
    
    replaceCharacter(s+1, c1, c2);
}
Code language: C++ (cpp)

Leave a Comment