Modify string by replacing all occurrences of given characters by specified replacing characters | C ++ program for the above approach ; Function to modify given string by replacing characters ; Store the size of string and the number of pairs ; Initialize 2 character arrays ; Traverse the string s Update arrays arr [ ] and brr [ ] ; Traverse the array of pairs p ; a -> Character to be replaced b -> Replacing character ; Iterate over the range [ 0 , 25 ] ; If it is equal to current character , then replace it in the array b ; Print the array brr [ ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void replaceCharacters ( string s , vector < vector < char > > p ) { int n = s . size ( ) , k = p . size ( ) ; char arr [ 26 ] ; char brr [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ s [ i ] - ' a ' ] = s [ i ] ; brr [ s [ i ] - ' a ' ] = s [ i ] ; } for ( int j = 0 ; j < k ; j ++ ) { char a = p [ j ] [ 0 ] , b = p [ j ] [ 1 ] ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( arr [ i ] == a ) { brr [ i ] = b ; } } } for ( int i = 0 ; i < n ; i ++ ) { cout << brr [ s [ i ] - ' a ' ] ; } } int main ( ) { string S = " aabbgg " ; vector < vector < char > > P { { ' a ' , ' b ' } , { ' b ' , ' g ' } , { ' g ' , ' a ' } } ; replaceCharacters ( S , P ) ; return 0 ; }