以下是我用於方法lastIndexOf
,ch
的字符是匹配的字符,並且str
是源字符串。java遞歸查找字符串中字符的最後一個索引
public static int lastIndexOf(char ch, String str) {
// check for null string or empty string
if (str.length() == 0 || str == null) {
return -1;
}
int indexInRest = lastIndexOf(ch, str.substring(1));
char first = str.charAt(0);
// recursive call to find the last matching character
if (first == ch) {
return 1 + indexInRest; // this might not work properly
} else
return indexInRest;
}
如果在我的課的主要方法,我稱之爲:
System.out.println(lastIndexOf('r', "recurse"));
System.out.println(lastIndexOf('p', "recurse"));
我:
1
-1
期望的結果是:
4
-1
建議,請。
是這個家庭作業? – user1329572
以及現有方法有什麼問題http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#lastIndexOf%28int%29? –
是的,我需要建議。 – Hank