text: Count occurrences of substring X before every occurrence of substring Y in a given string | Java program for the above approach ; Function to count occurrences of the string Y in the string S for every occurrence of X in S ; Stores the count of occurrences of X ; Stores the lengths of the three strings ; Traverse the string S ; If the current substring is Y , then increment the value of count by 1 ; If the current substring is X , then print the count ; Driver Code
code: import java . io . * ; import java . lang . * ; import java . util . * ; public class GFG { static void countOccurrences ( String S , String X , String Y ) { int count = 0 ; int N = S . length ( ) , A = X . length ( ) ; int B = Y . length ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( S . substring ( i , Math . min ( N , i + B ) ) . equals ( Y ) ) count ++ ; if ( S . substring ( i , Math . min ( N , i + A ) ) . equals ( X ) ) System . out . print ( count + " ▁ " ) ; } } public static void main ( String [ ] args ) { String S = " abcdefdefabc " ; String X = " abc " ; String Y = " def " ; countOccurrences ( S , X , Y ) ; } }