text: Count occurrences of substring X before every occurrence of substring Y in a given string | C # 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: using System ; 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 ; int P = Math . Min ( A , Math . Min ( N , B ) ) ; for ( int i = 0 ; i < N - P + 1 ; i ++ ) { if ( S . Substring ( i , Math . Min ( N , B ) ) . Equals ( Y ) ) count ++ ; if ( S . Substring ( i , Math . Min ( N , A ) ) . Equals ( X ) ) Console . Write ( count + " ▁ " ) ; } } public static void Main ( string [ ] args ) { string S = " abcdefdefabc " ; string X = " abc " ; string Y = " def " ; countOccurrences ( S , X , Y ) ; } }