Peter said:
Hmmm...it seems to me that this problem needs a recursive solution
like calculating Fibonacci numbers does.
Here's a linear recursion that would be quite sensible in some other
language. I'm not twisted enough to come up with one that does as much
repeat work as those textbook Fibonacci functions you have in mind.
I threw in a boolean parameter to specify whether overlaps count:
$ java -cp . Cont bananana nan 2 true ==> 4
$ java -cp . Cont bananana nan 2 false ==> -1
(This indexes the first occurrence as 1, so those look for the
second. The return value is the usual 0-based index to the string.)
class Cont {
private final String s; Cont (String t) { s = t ; }
int indexOfNth(String str, int n, int fromIndex, boolean overlapping) {
int first = s.indexOf(str, fromIndex);
return (first == -1) ? -1
: (n == 1) ? first
: indexOfNth(str, n - 1,
first + (overlapping ? 1 : str.length()),
overlapping);
}
int indexOfNth(String str, int n, boolean overlapping) {
return indexOfNth(str, n, 0, overlapping);
}
public static void main(String [] args) {
System.out.
println(new Cont(args[0])
.indexOfNth(args[1],
Integer.parseInt(args[2]),
Boolean.valueOf(args[3])));
}
}