Home  >  Article  >  Java  >  Count the number of occurrences of a substring recursively in Java

Count the number of occurrences of a substring recursively in Java

王林
王林forward
2023-09-17 19:49:021087browse

Count the number of 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 procedure.

A recursive function is a function that calls itself within its definition.

If str1 is "I know that you know that i know", str2 is "know"

The number of occurrences is - 3

Let us use examples understand.

For example, the Chinese translation of

input

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

output

Count of occurrences of a substring recursively are: 4

Explanation

is:

Explanation

The substring TP occurs 4 times in str1.

Input

str1 = "HiHOwAReyouHiHi" str2 = "Hi"

Output

Count of occurrences of a substring recursively are: 3

The Chinese translation of Explanation

is:

Explanation

The substring Hi occurs 3 times in str1.

In the following program The method used is as follows -

In this method, we will search for the occurrence of str2 in str1 using the contains() method in java. Returns true if str2 exists in str1. If true, remove the first match from str1 by replacing it with "" using the ReplaceFirst() method in java and adding 1 to the return value to increase the count.

  • Take two strings as str1 and str2.

  • The recursive method subsrting_rec(String str, String sub) accepts the string str and its substring sub and returns the number of times sub appears in str.

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

  • If true, use str.replaceFirst(sub,"") to replace the first occurrence of sub with "".

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

  • At the end of all recursions, the sum of all returned values ​​is count .

  • Print the result.

Example

Live Demonstration

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

The above is the detailed content of Count the number of occurrences of a substring recursively in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete