Count occurrences of a substring recursively | Recursive C ++ 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 function
#include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; int countSubstrig ( string str1 , string str2 ) { int n1 = str1 . length ( ) ; int n2 = str2 . length ( ) ; if ( n1 == 0 n1 < n2 ) return 0 ; if ( str1 . substr ( 0 , n2 ) . compare ( str2 ) == 0 ) return countSubstrig ( str1 . substr ( n2 - 1 ) , str2 ) + 1 ; return countSubstrig ( str1 . substr ( n2 - 1 ) , str2 ) ; } int main ( ) { string str1 = " geeksforgeeks " , str2 = " geeks " ; cout << countSubstrig ( str1 , str2 ) << endl ; str1 = " hikakashi " , str2 = " hi " ; cout << countSubstrig ( str1 , str2 ) << endl ; return 0 ; }