In: Computer Science
USE JAVA PLEASE
Use recursion to implement a method
public static int indexOf(String text, String str)
that returns the starting position of the first substring of the
text that matches str.
Return –1 if str is not a substring of the text.
For example, s.indexOf("Mississippi", "sip") returns 6.
Hint: You must keep track of how far the match is from the beginning of the text. Make that value a parameter variable of a helper method.
Ans)
public int indexOf(String text, String str){
if
(text.substring(0,str.length()).equals(str.substring(0,str.length()))){
// if first character
return 0;
}
if (text.length() <= 0 || str.length() <= 0)
return -1;
if (str.length() > text.length()){
return -1;
}
if (text.length() <= 1)
return -1;
return (1 + indexOf(text.substring(1,text.length()), str.substring(0,str.length())));
// check second characracter and so on
}
/* PROGRAM */
public class Test {
public int indexOf(String text, String str){
if
(text.substring(0,str.length()).equals(str.substring(0,str.length()))){
return 0;
}
if (text.length() <= 0 || str.length() <= 0)
return -1;
if (str.length() > text.length()){
return -1;
}
if (text.length() <= 1)
return -1;
return (1 + indexOf(text.substring(1,text.length()),
str.substring(0,str.length())));
}
public static void main(String[] args) {
Test s = new Test();
System.out.println(s.indexOf("Mississippi", "sip"));
}
}
/* PLEASE UPVOTE */