In: Computer Science
use java recursion
find # of times a substring is in a string but it has to be the exact same, no extra letters attached to it and capitalization matters.
input: school is boring with schooling and School
substring: school
output: 1
import java.util.*;
class Main
{
//recursive function to count occurance of substrig
static int countSubstr(String str1, String str2)
{
//length of input string
int n1 = str1.length();
//length of substring
int n2 = str2.length();
//base case
if (n1 == 0 || n1 < n2)
return 0;
//recursive case
//checkes if the first substring match or not
if (str1.substring(0, n2).equals(str2))
return countSubstr(str1.substring(n2 - 1), str2) + 1;
//otherwise, return the count from the remaining index
return countSubstr(str1.substring(n2 - 1), str2);
}
//main function
public static void main(String args[])
{
//to store input string and substring
String input, substring;
Scanner sc = new Scanner(System.in);
//input String
System.out.print("Input: ");
input = sc.nextLine();
//substring
System.out.print("substring: ");
substring = sc.nextLine();
int count = countSubstr(input, substring);
//function call and prints counts
System.out.println("output: " + count);
}
}
Please refer below screenshot of code for better understanding of indentation.
Sample output :