Replace two substrings ( of a string ) with each other | Java implementation of the approach ; Function to return the resultant string ; Iterate through all positions i ; Current sub - string of length = len ( A ) = len ( B ) ; If current sub - string gets equal to A or B ; Update S after replacing A ; Update S after replacing B ; Return the updated string ; Driver code
class GFG { static String updateString ( String S , String A , String B ) { int l = A . length ( ) ; for ( int i = 0 ; i + l <= S . length ( ) ; i ++ ) { String curr = S . substring ( i , i + l ) ; if ( curr . equals ( A ) ) { String new_string = S . substring ( 0 , i ) + B + S . substring ( i + l , S . length ( ) ) ; S = new_string ; i += l - 1 ; } else { String new_string = S . substring ( 0 , i ) + A + S . substring ( i + l , S . length ( ) ) ; S = new_string ; i += l - 1 ; } } return S ; } public static void main ( String [ ] args ) { String S = " aab " ; String A = " aa " ; String B = " bb " ; System . out . println ( updateString ( S , A , B ) ) ; } }