Write a recursive method called indexOf that accepts two strings as parameters and that returns the starting index of the first occurrence of the second string inside the first string (or 1 if not found). For example, the call of indexOf("Barack Obama", "bam")would return 8. (Strings already have an indexOf method, but you may not call it in your solution.)
// package recursion;
public class StringIndex {
public static int indexOf(String string1, String string2) {
// check if string1 is less than string2
if (string1.length() < string2.length())
return -1;
// check if substring of string1 equals string2
boolean equals = string1.substring(0, string2.length()).equals(string2);
if (equals)
return 0;
//take the substring starting from index 1 in the string1 variable
string1 = string1.substring(1);
// recursive call on index
int index = indexOf(string1, string2);
if (index == -1)
return -1;
return 1 + index;
}
public static void main(String[] args) {
String string1 = "is there anybody here?";
String string2 = "any";
System.out.print("the string \""+string2+"\" repeats again in the string \""+string1+"\" at index: ");
System.out.println(indexOf(string1, string2));
}
}
Output:
the string "any" repeats again in the string "is there anybody here?" at index: 9