Minimum characters to be replaced to remove the given substring | C ++ implementation of above approach ; function to calculate minimum characters to replace ; mismatch occurs ; if all characters matched , i . e , there is a substring of ' a ' which is same as string ' b ' ; increment i to index m - 1 such that minimum characters are replaced in ' a ' ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int replace ( string A , string B ) { int n = A . length ( ) , m = B . length ( ) ; int count = 0 , i , j ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < m ; j ++ ) { if ( A [ i + j ] != B [ j ] ) break ; } if ( j == m ) { count ++ ; i += m - 1 ; } } return count ; } int main ( ) { string str1 = " aaaaaaaa " ; string str2 = " aaa " ; cout << replace ( str1 , str2 ) ; return 0 ; }