Skip to content
Related Articles
Open in App
Not now

Related Articles

C++ Program to Replace a Character in a String

Improve Article
Save Article
Like Article
  • Last Updated : 27 Jan, 2023
Improve Article
Save Article
Like Article

Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. 
Examples:

Input: grrksfoegrrks,
       c1 = e, c2 = r 
Output: geeksforgeeks 

Input: ratul,
       c1 = t, c2 = h 
Output: rahul

Traverse through the string and check for the occurrences of c1 and c2. If c1 is found then replace it with c2 and else if c2 is found replace it with c1.

C++




// C++ program to replace c1 with c2
// and c2 with c1
#include <bits/stdc++.h>
using namespace std;
string replace(string s,
               char c1, char c2)
{
    int l = s.length();
 
    // loop to traverse in the string
    for (int i = 0; i < l; i++)
    {
        // check for c1 and replace
        if (s[i] == c1)
            s[i] = c2;
 
        // check for c2 and replace
        else if (s[i] == c2)
            s[i] = c1;
    }
    return s;
}
 
// Driver code
int main()
{
    string s = "grrksfoegrrks";
    char c1 = 'e', c2 = 'r';
    cout << replace(s, c1, c2);
    return 0;
}

Output:

geeksforgeeks

Time Complexity: O(n) 
Auxiliary Space: O(n), because the program creates a copy of string s.

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!