Replace a character c1 with c2 and c2 with c1 in a string S

15 Jun, 2022
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++
Java
Python3
C#
PHP
Javascript
// CPP 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 to check the above functionint main(){    string s = "grrksfoegrrks";    char c1 = 'e', c2 = 'r';    cout << replace(s, c1, c2);    return 0;}
// Java program to replace c1 with c2// and c2 with c1class GFG{     static String replace(String s,                    char c1, char c2){    int l = s.length();    char []arr = s.toCharArray();         // loop to traverse in the string    for (int i = 0; i < l; i++)    {             // check for c1 and replace        if (arr[i] == c1)            arr[i] = c2;                     // check for c2 and replace        else if (arr[i] == c2)            arr[i] = c1;    }         return String.valueOf(arr);} // Driver codepublic static void main(String []args){    String s = "grrksfoegrrks";    char c1 = 'e', c2 = 'r';    System.out.println(replace(s, c1, c2));}} // This code is contributed// by ChitraNayal
# Python3 program to replace c1 with c2# and c2 with c1def replace(s, c1, c2):    l = len(s)         # loop to traverse in the string    for i in range(l):                 # check for c1 and replace        if (s[i] == c1):            s = s[0:i] + c2 + s[i + 1:]                 # check for c2 and replace        elif (s[i] == c2):            s = s[0:i] + c1 + s[i + 1:]    return s # Driver Codeif __name__ == '__main__':    s = "grrksfoegrrks"    c1 = 'e'    c2 = 'r'    print(replace(s, c1, c2)) # This code is contributed# by PrinciRaj1992
// C# program to replace c1 with c2// and c2 with c1using System;public class GFG{     static String replace(String s,                        char c1, char c2)    {        int l = s.Length;        char []arr = s.ToCharArray();         // loop to traverse in the string        for (int i = 0; i < l; i++)        {             // check for c1 and replace            if (arr[i] == c1)                arr[i] = c2;                             // check for c2 and replace            else if (arr[i] == c2)                arr[i] = c1;        }         return string.Join("", arr);    }     // Driver code    public static void Main()    {        String s = "grrksfoegrrks";        char c1 = 'e', c2 = 'r';        Console.WriteLine(replace(s, c1, c2));    }}// This code is contributed by 29AjayKumar
<?php// PHP program to replace c1// with c2 and c2 with c1function replace($s, $c1, $c2){    $l = strlen($s);     // loop to traverse    // in the string    for ($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$s = "grrksfoegrrks";$c1 = 'e'; $c2 = 'r';echo replace($s, $c1, $c2); // This code is contributed by anuj_67.?>
<script>// Javascript program to replace c1 with c2// and c2 with c1         function replace(s,c1,c2)    {        let l = s.length;    let arr = s.split("");           // loop to traverse in the string    for (let i = 0; i < l; i++)    {               // check for c1 and replace        if (arr[i] == c1)            arr[i] = c2;                       // check for c2 and replace        else if (arr[i] == c2)            arr[i] = c1;    }           return arr.join("");    }         // Driver code    let s = "grrksfoegrrks";    let c1 = 'e', c2 = 'r';    document.write(replace(s, c1, c2));         // This code is contributed by rag2127</script>
Output: 
geeksforgeeks
Time Complexity: O(n) 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Auxiliary Space: 0(1) 
Replace a character c1 with c2 and c2 with c1 in a string S | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersReplace a character c1 with c2 and c2 with c1 in a string S | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:31•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=_dy1oByB_b8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
vt_m
ukasp
29AjayKumar
princiraj1992
gfg_sal_gfg
rag2127
geekygirl2001
School Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Constructors in Java
Exceptions in Java
Python Exception Handling
Python Try Except
Ternary Operator in Python
Write a program to reverse an array or string
Write a program to print all permutations of a given string
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching