Minimum characters to be replaced to remove the given substring | Java 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
import java . io . * ; class GFG { static 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 ( i + j >= n ) break ; else if ( A . charAt ( i + j ) != B . charAt ( j ) ) break ; } if ( j == m ) { count ++ ; i += m - 1 ; } } return count ; } public static void main ( String args [ ] ) { String str1 = " aaaaaaaa " ; String str2 = " aaa " ; System . out . println ( replace ( str1 , str2 ) ) ; } }