Count occurrences of a substring recursively | Recursive Java program for counting number of substrings ; Recursive function to count the number of occurrences of " hi " in str . ; Base Case ; Recursive Case Checking if the first substring matches ; Otherwise , return the count from the remaining index ; Driver Code
class GFG { static int countSubstrig ( String str1 , String str2 ) { int n1 = str1 . length ( ) ; int n2 = str2 . length ( ) ; if ( n1 == 0 n1 < n2 ) return 0 ; if ( str1 . substring ( 0 , n2 ) . equals ( str2 ) ) return countSubstrig ( str1 . substring ( n2 - 1 ) , str2 ) + 1 ; return countSubstrig ( str1 . substring ( n2 - 1 ) , str2 ) ; } public static void main ( String args [ ] ) { String str1 = " geeksforgeeks " , str2 = " geeks " ; System . out . println ( countSubstrig ( str1 , str2 ) ) ; str1 = " hikakashi " ; str2 = " hi " ; System . out . println ( countSubstrig ( str1 , str2 ) ) ; } }