Table of Contents
input
output
Explanation
Input
Output
The Chinese translation of Explanation
Example
Home Java javaTutorial Count the number of occurrences of a substring recursively in Java

Count the number of occurrences of a substring recursively in Java

Sep 17, 2023 pm 07:49 PM
recursion calculate substring

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";
Copy after login

output

Count of occurrences of a substring recursively are: 4
Copy after login
Copy after login

Explanation

is:

Explanation

The substring TP occurs 4 times in str1.
Copy after login

Input

str1 = "HiHOwAReyouHiHi" str2 = "Hi"
Copy after login

Output

Count of occurrences of a substring recursively are: 3
Copy after login

The Chinese translation of Explanation

is:

Explanation

The substring Hi occurs 3 times in str1.
Copy after login

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;
   }
}
Copy after login

Output

If we run the above code, it will generate the following output-

Count of occurrences of a substring recursively are: 4
Copy after login
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recursive implementation of C++ functions: Is there a limit to recursion depth? Recursive implementation of C++ functions: Is there a limit to recursion depth? Apr 23, 2024 am 09:30 AM

The recursion depth of C++ functions is limited, and exceeding this limit will result in a stack overflow error. The limit value varies between systems and compilers, but is usually between 1,000 and 10,000. Solutions include: 1. Tail recursion optimization; 2. Tail call; 3. Iterative implementation.

CUDA's universal matrix multiplication: from entry to proficiency! CUDA's universal matrix multiplication: from entry to proficiency! Mar 25, 2024 pm 12:30 PM

General Matrix Multiplication (GEMM) is a vital part of many applications and algorithms, and is also one of the important indicators for evaluating computer hardware performance. In-depth research and optimization of the implementation of GEMM can help us better understand high-performance computing and the relationship between software and hardware systems. In computer science, effective optimization of GEMM can increase computing speed and save resources, which is crucial to improving the overall performance of a computer system. An in-depth understanding of the working principle and optimization method of GEMM will help us better utilize the potential of modern computing hardware and provide more efficient solutions for various complex computing tasks. By optimizing the performance of GEMM

How to calculate addition, subtraction, multiplication and division in word document How to calculate addition, subtraction, multiplication and division in word document Mar 19, 2024 pm 08:13 PM

WORD is a powerful word processor. We can use word to edit various texts. In Excel tables, we have mastered the calculation methods of addition, subtraction and multipliers. So if we need to calculate the addition of numerical values ​​in Word tables, How to subtract the multiplier? Can I only use a calculator to calculate it? The answer is of course no, WORD can also do it. Today I will teach you how to use formulas to calculate basic operations such as addition, subtraction, multiplication and division in tables in Word documents. Let's learn together. So, today let me demonstrate in detail how to calculate addition, subtraction, multiplication and division in a WORD document? Step 1: Open a WORD, click [Table] under [Insert] on the toolbar, and insert a table in the drop-down menu.

Do C++ lambda expressions support recursion? Do C++ lambda expressions support recursion? Apr 17, 2024 pm 09:06 PM

Yes, C++ Lambda expressions can support recursion by using std::function: Use std::function to capture a reference to a Lambda expression. With a captured reference, a Lambda expression can call itself recursively.

How to count the number of elements in a list using Python's count() function How to count the number of elements in a list using Python's count() function Nov 18, 2023 pm 02:53 PM

How to use Python's count() function to calculate the number of an element in a list requires specific code examples. As a powerful and easy-to-learn programming language, Python provides many built-in functions to handle different data structures. One of them is the count() function, which can be used to count the number of elements in a list. In this article, we will explain how to use the count() function in detail and provide specific code examples. The count() function is a built-in function of Python, used to calculate a certain

How to use the Math.Pow function in C# to calculate the power of a specified number How to use the Math.Pow function in C# to calculate the power of a specified number Nov 18, 2023 am 11:32 AM

In C#, there is a Math class library, which contains many mathematical functions. These include the function Math.Pow, which calculates powers, which can help us calculate the power of a specified number. The usage of the Math.Pow function is very simple, you only need to specify the base and exponent. The syntax is as follows: Math.Pow(base,exponent); where base represents the base and exponent represents the exponent. This function returns a double type result, that is, the power calculation result. Let's

Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Apr 22, 2024 pm 03:18 PM

The recursive algorithm solves structured problems through function self-calling. The advantage is that it is simple and easy to understand, but the disadvantage is that it is less efficient and may cause stack overflow. The non-recursive algorithm avoids recursion by explicitly managing the stack data structure. The advantage is that it is more efficient and avoids the stack. Overflow, the disadvantage is that the code may be more complex. The choice of recursive or non-recursive depends on the problem and the specific constraints of the implementation.

Detailed explanation of C++ function recursion: application of recursion in string processing Detailed explanation of C++ function recursion: application of recursion in string processing Apr 30, 2024 am 10:30 AM

A recursive function is a technique that calls itself repeatedly to solve a problem in string processing. It requires a termination condition to prevent infinite recursion. Recursion is widely used in operations such as string reversal and palindrome checking.

See all articles