Find and Replace all occurrence of a substring in the given String | C ++ program for the above approach ; Function to replace all the occurrences of the substring S1 to S2 in string S ; Stores the resultant string ; Traverse the string s ; If the first character of string s1 matches with the current character in string s ; If the complete string matches or not ; If complete string matches then replace it with the string s2 ; Otherwise ; Otherwise ; Print the resultant string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void modifyString ( string & s , string & s1 , string & s2 ) { string ans = " " ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int k = 0 ; if ( s [ i ] == s1 [ k ] && i + s1 . length ( ) <= s . length ( ) ) { int j ; for ( j = i ; j < i + s1 . length ( ) ; j ++ ) { if ( s [ j ] != s1 [ k ] ) { break ; } else { k = k + 1 ; } } if ( j == i + s1 . length ( ) ) { ans . append ( s2 ) ; i = j - 1 ; } else { ans . push_back ( s [ i ] ) ; } } else { ans . push_back ( s [ i ] ) ; } } cout << ans ; } int main ( ) { string S = " geeksforgeeks " ; string S1 = " eek " ; string S2 = " ok " ; modifyString ( S , S1 , S2 ) ; return 0 ; }