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