Count occurrences of substring X before every occurrence of substring Y in a given string | 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
def countOccurrences ( S , X , Y ) : NEW_LINE INDENT count = 0 NEW_LINE N = len ( S ) NEW_LINE A = len ( X ) NEW_LINE B = len ( Y ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( S [ i : i + B ] == Y ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( S [ i : i + A ] == X ) : NEW_LINE INDENT print ( count , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT S = " abcdefdefabc " NEW_LINE X = " abc " NEW_LINE Y = " def " NEW_LINE countOccurrences ( S , X , Y ) NEW_LINE