Replace two substrings ( of a string ) with each other | C # 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
using System ; 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 , l ) ; if ( curr . Equals ( A ) ) { string new_string = S . Substring ( 0 , i ) + B + S . Substring ( i + l ) ; S = new_string ; i += l - 1 ; } else { string new_string = S . Substring ( 0 , i ) + A + S . Substring ( i + l ) ; S = new_string ; i += l - 1 ; } } return S ; } public static void Main ( ) { string S = " aab " ; string A = " aa " ; string B = " bb " ; Console . WriteLine ( updateString ( S , A , B ) ) ; } }