Replace a character c1 with c2 and c2 with c1 in a string S | Java 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
class GFG { static String replace ( String s , char c1 , char c2 ) { int l = s . length ( ) ; char [ ] arr = s . toCharArray ( ) ; for ( int i = 0 ; i < l ; i ++ ) { if ( arr [ i ] == c1 ) arr [ i ] = c2 ; else if ( arr [ i ] == c2 ) arr [ i ] = c1 ; } return String . valueOf ( arr ) ; } public static void main ( String [ ] args ) { String s = " grrksfoegrrks " ; char c1 = ' e ' , c2 = ' r ' ; System . out . println ( replace ( s , c1 , c2 ) ) ; } }