Count occurrences of a substring recursively

06 May, 2022
Given two strings str1 and str2, the task is to count the number of times str2 occurs in str1 using recursion.
Examples: 
Input: str1 = “geeksforgeeks”, str2 = “geek”Output: 2Explanation: The occurrences of str2 in str1 are starting at index {0, 8}
Input: str1 = “aaaaa”, str2 = “aaa”Output: 3Explanation: The occurrences of str2 in str1 are starting at index {0,1,2
Approach: We have already discussed other approaches in our previous article but here we are going to solve this problem using recursion.
Algorithm: 
If size of string str2 is greater then string str1 or size of string str1 is 0 then, return 0.
Otherwise, Check if string str2 is present in str1 as substring or not.if present then, increment the count of occurrence and recursively call for other substring.else, recursively call for other substring.return count from every recursively call as answer.
if present then, increment the count of occurrence and recursively call for other substring.
else, recursively call for other substring.
return count from every recursively call as answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// Recursive C++ program to count the number of// times string str2 occurs in string str1 #include <iostream>#include <string>using namespace std; // Function to count the number of// times string str2 occurs in string str1int countSubstring(string str1, string str2){    int n1 = str1.length();    int n2 = str2.length();     // Base Case    if (n1 == 0 || n1 < n2)        return 0;     // Recursive Case    // Checking if the first substring matches    if (str1.substr(0, n2).compare(str2) == 0)        return countSubstring(str1.substr(1), str2) + 1;     // Otherwise, return the count from    // the remaining index    return countSubstring(str1.substr(1), str2);}  // Driver functionint main(){    string str1 = "geeksforgeeks", str2 = "geeks";    cout << countSubstring(str1, str2) << endl;         str1 = "aaaaa", str2 = "aaa";    cout << countSubstring(str1, str2) << endl;     return 0;}
// Recursive Java program for// counting number of substringsclass GFG{ // Recursive function to// count the number of// occurrences of "hi" in str.static int countSubstring(String str1,                         String str2){    int n1 = str1.length();    int n2 = str2.length();     // Base Case    if (n1 == 0 || n1 < n2)        return 0;     // Recursive Case    // Checking if the first    // substring matches    if (str1.substring(0, n2).equals(str2))        return countSubstring(str1.substring(1),                                            str2) + 1;     // Otherwise, return the count    // from the remaining index    return countSubstring(str1.substring(1),                                        str2);} // Driver Codepublic static void main(String args[]){    String str1 = "geeksforgeeks",           str2 = "geeks";    System.out.println(countSubstring(str1,                                     str2));     str1 = "aaaaa";    str2 = "aaa";    System.out.println(countSubstring(str1,                                     str2)); }} // This code is contributed// by Arnab Kundu
# Recursive Python3 program for# counting number of substrings # Recursive function to# count the number of# occurrences of "hi" in str.def countSubstring(str1, str2):         n1 = len(str1);    n2 = len(str2);         # Base Case    if (n1 == 0 or n1 < n2):        return 0;     # Recursive Case    # Checking if the first    # substring matches    if (str1[0 : n2] == str2):        return countSubstring(str1[1:],                             str2) + 1;     # Otherwise, return the count    # from the remaining index    return countSubstring(str1[1:],                         str2); # Driver Codeif __name__ == '__main__':         str1 = "geeksforgeeks";    str2 = "geeks";    print(countSubstring(str1, str2));     str1 = "aaaaa";    str2 = "aaa";    print(countSubstring(str1, str2)); # This code is contributed by Princi Singh
// Recursive C# program for// counting number of substringsusing System;class GFG{ // Recursive function to// count the number of// occurrences of "hi" in str.static int countSubstring(String str1,                         String str2){    int n1 = str1.Length;    int n2 = str2.Length;     // Base Case    if (n1 == 0 || n1 < n2)        return 0;     // Recursive Case    // Checking if the first    // substring matches    if (str1.Substring(0, n2).Equals(str2))        return countSubstring(str1.Substring(1),                                            str2) + 1;     // Otherwise, return the    // count from the remaining    // index    return countSubstring(str1.Substring(1),                                        str2);} // Driver Codepublic static void Main(){    string str1 = "geeksforgeeks",           str2 = "geeks";    Console.Write(countSubstring(str1,                                str2));    Console.Write("\n");         str1 = "aaaaa";    str2 = "aaa";    Console.Write(countSubstring(str1,                                str2)); }} // This code is contributed// by Smita
<script> // Recursive js program for counting number of substrings // Recursive function to count// the number of occurrences of "hi" in str.function countSubstring( str1, str2){    let n1 = str1.length;    let n2 = str2.length;     // Base Case    if (n1 == 0 || n1 < n2)        return 0;     // Recursive Case    // Checking if the first substring matches    if (str1.substr(0, n2) == (str2))        return countSubstring(str1.substr(1), str2) + 1;     // Otherwise, return the count from    // the remaining index    return countSubstring(str1.substr(1), str2);} // Driver functionlet str1 = "geeksforgeeks", str2 = "geeks";document.write( countSubstring(str1, str2),'<br>');str1 = "aaaaa", str2 = "aaa";document.write( countSubstring(str1, str2),'<br>');  </script>
2
3
Time Complexity: O(N2) , (i.e. N is maximum length between str1 and str2)Auxiliary Space: O(1)
andrew1234
Smitha Dinesh Semwal
princi singh
rohitsingh07052
kunwarhardik1999
sagartomar9927
avtarkumar719
germanshephered48
cpp-string
Recursion
Strings
Strings
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.