Replace all occurrences of character X with character Y in given string

27 May, 2022
Given a string str and two characters X and Y, the task is to write a recursive function to replace all occurrences of character X with character Y.
Examples: 
Input: str = abacd, X = a, Y = x Output: xbxcd
Input: str = abacd, X = e, Y = y Output: abacd  
Iterative Approach: The idea is to iterate over the given string and if any character X is found then replace that character with Y.
Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time.Auxiliary Space: O(1), as we are not using any extra space.
Recursive Approach: The idea is to recursively traverse the given string and replace the character with value X with Y. Below are the steps:
Get the string str, character X, and Y.Recursively Iterate from index 0 to string length.Base Case: If we reach the end of the string the exit from the function.  
Get the string str, character X, and Y.
Recursively Iterate from index 0 to string length.Base Case: If we reach the end of the string the exit from the function.  
Base Case: If we reach the end of the string the exit from the function.  
if(str[0]=='\0')
   return ;
Recursive Call: If the base case is not met, then check for the character at 0th index if it is X then replace that character with Y and recursively iterate for next character.  
if(str[0]==X) 
  str[0] = Y
Return Statement: At each recursive call(except the base case), return the recursive function for the next iteration.  
return recursive_function(str + 1, X, Y)
Below is the recursive implementation:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to replace all occurrences// of character c1 with character c2void replaceCharacter(char input[],                    char c1, char c2){    // Base Case    // If the string is empty    if (input[0] == '\0') {        return;    }     // If the character at starting    // of the given string is equal    // to c1, replace it with c2    if (input[0] == c1) {        input[0] = c2;    }     // Getting the answer from recursion    // for the smaller problem    return replaceCharacter(input + 1,                            c1, c2);} // Driver Codeint main(){    // Given string    char str[] = "abacd";    char c1 = 'a';    char c2 = 'x';     // Function call    replaceCharacter(str, c1, c2);     // Print the string    cout << str;    return 0;}
// Java program for the above approachimport java.util.*;import java.io.*; class GFG{     // Function to replace all occurrences// of character c1 with character c2static String replaceCharacter(String str,                             char c1, char c2){    // Base Case    // If the string is empty    if (str.length() == 1)    {        return str;    }    char x=str.charAt(0);    // If the character at starting    // of the given string is equal    // to c1, replace it with c2    if (str.charAt(0) == c1)    {        x=c2;        str = c2+str.substring(1);    }     // Getting the answer from recursion    // for the smaller problem    return x+replaceCharacter(str.substring(1),                            c1, c2);} // Driver Codepublic static void main(String[] args){         // Given string    String str = "abacd";    char c1 = 'a';    char c2 = 'x';     // Function call    System.out.println(replaceCharacter(str, c1, c2));}} // This code is contributed by cyrus18
# Python3 program for the above approach # Function to replace all occurrences# of character c1 with character c2def replaceCharacter(input, c1, c2):         input = list(str)         # If the character at starting    # of the given string is equal    # to c1, replace it with c2    for i in range(0, len(str)):        if (input[i] == c1):            input[i] = c2;                     # Print the string        print(input[i], end = "")     # Driver Code # Given stringstr = "abacd"c1 = 'a'c2 = 'x' # Function callreplaceCharacter(str, c1, c2); # This code is contributed by sanjoy_62
// C# program for the above approachusing System; class GFG{     // Function to replace all occurrences// of character c1 with character c2static void replaceCharacter(string str,                             char c1, char c2){    char[] input = str.ToCharArray();     // If the character at starting    // of the given string is equal    // to c1, replace it with c2    for(int i = 0; i < str.Length; i++)    {        if (input[i] == c1)        {            input[i] = c2;        }             // Print the string        Console.Write(input[i]);    }} // Driver Codepublic static void Main(){         // Given string    string str = "abacd";    char c1 = 'a';    char c2 = 'x';     // Function call    replaceCharacter(str, c1, c2);}} // This code is contributed by sanjoy_62
<script>// javascript program for the above approach      // Function to replace all occurrences// of character c1 with character c2function replaceCharacter(str,c1, c2){    // Base Case    // If the string is empty    if (str.length == 1)    {        return str;    }    var x=str.charAt(0);    // If the character at starting    // of the given string is equal    // to c1, replace it with c2    if (str.charAt(0) == c1)    {        x=c2;        str = c2+str.substring(1);    }     // Getting the answer from recursion    // for the smaller problem    return x+replaceCharacter(str.substring(1),                            c1, c2);} // Driver Code//Given stringvar str = "abacd";var c1 = 'a';var c2 = 'x'; // Function calldocument.write(replaceCharacter(str, c1, c2)); // This code is contributed by 29AjayKumar</script>
xbxcd
Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time, where N is the length of the string.Auxiliary Space: O(N), due to recursive stack space.
sanjoy_62
cyrus18
29AjayKumar
rohitsingh07052
Competitive Programming
Recursion
Strings
Strings
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
Bits manipulation (Important tactics)
What is Competitive Programming and How to Prepare for It?
Algorithm Library | C++ Magicians STL Algorithm
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction