Count occurrences of a substring recursively in Java


Given two strings str_1 and str_2. The goal is to count the number of occurrences of substring str2 in string str1 using a recursive process.

A recursive function is the one which has its own call inside it’s definition.

If str1 is “I know that you know that i know” str2=”know”

Count of occurences is − 3

Let us understand with examples.

For Example

Input

str1 = "TPisTPareTPamTP", str2 = "TP";

Output

Count of occurrences of a substring recursively are: 4

Explanation

The substring TP occurs 4 times in str1.

Input

str1 = "HiHOwAReyouHiHi" str2 = "Hi"

Output

Count of occurrences of a substring recursively are: 3

Explanation

The substring Hi occurs 3 times in str1.

Approach used in the below program is as follows

In this approach we will search for occurrence of str2 in str1 using contains() method in java. It will return true if str2 exists in str1. In case true, remove that first occurrence from str1 by replacing it with “” using replaceFirst() method in java and add 1 to return value to increase count.

  • Take two strings as str1 and str2.

  • Recursive Method subsrting_rec(String str, String sub) takes string str and its substring sub and returns the count of occurrences of sub in str.

  • Check whether str.contains(sub) is true. ( str has sub )

  • If true then replace the first occurrence of sub with “” using str.replaceFirst(sub,””).

  • Do this inside a recursive call to subsrting_rec(String str, String sub).

  • At the end of all recursions the sum of all return values is count.

  • Print the result.

Example

 Live Demo

public class recursive{
   public static void main(String args[]){
      String str1 = "TPisTPareTPamTP", str2 = "TP";
      System.out.println("Count of occurrences of a substring recursively are: "+subsrting_rec(str1, str2));
   }
   static int subsrting_rec(String str, String sub){
      if (str.contains(sub)){
         return 1 + subsrting_rec(str.replaceFirst(sub, ""), sub);
      }
      return 0;
   }
}

Output

If we run the above code it will generate the following output −

Count of occurrences of a substring recursively are: 4

Updated on: 05-Jan-2021

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements