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

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.


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)
Auxiliary Space: O(1) 

Recursive Approach: The idea is to recursively traverse the given string and replace the character with value X with Y. Below are the steps:

  1. Get the string str, character X, and Y.
  2. Recursively Iterate from index 0 to string length.
    • Base Case: If we reach the end of the string the exit from the function.
         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.
        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++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to replace all occurrences
// of character c1 with character c2
void replaceCharacter(char input[],
                      char c1, char c2)
    // Base Case
    // If the string is empty
    if (input[0] == '\0') {
    // 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 Code
int 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;




Time Complexity: O(N), where N is the length of the string
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.