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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string updateString ( string S , string A , string B ) { int l = A . length ( ) ; for ( int i = 0 ; i + l <= S . length ( ) ; i ++ ) { string curr = S . substr ( i , i + l ) ; if ( curr == A ) { string new_string = " " ; new_string += S . substr ( 0 , i ) + B + S . substr ( i + l , S . length ( ) ) ; S = new_string ; i += l - 1 ; } else { string new_string = " " ; new_string += S . substr ( 0 , i ) + A + S . substr ( i + l , S . length ( ) ) ; S = new_string ; i += l - 1 ; } } return S ; } int main ( ) { string S = " aab " ; string A = " aa " ; string B = " bb " ; cout << ( updateString ( S , A , B ) ) << endl ; }