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 is 2 strings, output is an int
input: ("Hello it is hello it's me hellos" + "hi hellllloooo hi hello" + "hello", "hello")
should output: 3
input: (" Hello it is hello it's me hellos" + "hi hellllloooo hi hello" + "hello", "Hello")
should output: 1
input: (" Hello it is hello it's me hellos" + "hi hellllloooo hi hello" + "hello Hello ", "Hello")
should output: 2
input: (" HELLO it is hello it's me hellos" + "hi hellllloooo hi hello" + "hello Hello", "Hello")
should output: 1
input: (" HELLO it is hello it's me hellos" + "hi hellllloooo hi hello" + "hello Hello", "")
should output: 0
public class SubstringRecursion {
public static void main(String[] args) {
int times;
times = substring("Hello World Welcome to new World","",0);
System.out.println(times);
times = substring("king of Kings","king",0);
System.out.println(times);
String s = "I felt happy because I saw the others were happy and because I knew I should feel happy, but I wasn’t really happy";
times = substring(s, "happy", 0);
System.out.println(times);
}
public static int substring(String string, String substring, int index) {
if(substring.length()==0||string.length()==0)
return 0;
// if it has no matching then return 0
if(string.indexOf(substring)== -1) {
return 0;
}
// if string found we have to start checking from next character
int i = string.indexOf(substring)+1;
// adding 1 to new substring check
return 1 + substring(string.substring(i), substring, index + 1);
}
}
Code
Output