public class test {
public static int TindexOf(String source, String term) {
//System.out.println("Find indexOf(" + source + "," + term+ ")");
int ret = -1; // not found
boolean found = true;
if (source.length() < term.length())
return ret; // term can not be in source, source is too short
for (int i = 0; (i< term.length()) && found; i++)
if (source.charAt(i) != term.charAt(i)) {
//System.out.println(" mismatch at position " + i);
found = false;
}
if (found)
return 0; // match starting here
else
if (source.length() > 1) {
ret = indexOf(source.substring(1), term); // start search in rest of string
System.out.println("index of returned " + ret);
if (ret < 0)
ret = -1;
else
ret = ret + 1;
}
return ret;
}
public static int indexOf(String source, String term) {
int ret = -1; // not found
boolean found = true;
if (source.length() < term.length())
return ret; // term can not be in source, source is too short
for (int i = 0; (i< term.length()) && found; i++)
if (source.charAt(i) != term.charAt(i))
found = false;
if (found)
ret = 0; // match starting here
else
if (source.length() > 1) {
ret = indexOf(source.substring(1), term); // start search in rest of string
if (ret < 0)
ret = -1;
else // this recursively counts the starting position
ret = ret + 1;
}
return ret;
}
public static void main(String[] args) {
String a="alabama";
System.out.println("indexOf(alabama,alsa) = " + indexOf("alabama","alsa"));
System.out.println("indexOf(alabama,ala) = " + indexOf("alabama","ala"));
System.out.println("indexOf(alabama,aba) = " + indexOf("alabama","aba"));
System.out.println("indexOf(Barack Obama,bam) = " + indexOf("Barack Obama","bam"));
System.out.println("indexOf(Barack Obama,amabO) = " + indexOf("Barack Obama","amabO"));
System.out.println("indexOf(Barack Obama,B) = " + indexOf("Barack Obama","B"));
System.out.println("indexOf(Barack Obama,) = " + indexOf("Barack Obama",""));
System.out.println("a.indexOf(alabama,'') = " + a.indexOf(""));
}
}
|