【发布时间】:2012-09-19 09:57:44
【问题描述】:
这是我对方法 lastIndexOf 的内容,ch 是要匹配的字符,str 是源字符串。
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
请给个建议。
【问题讨论】:
-
是的,我需要建议。
-
您搜索的是从第一个字符到最后一个字符,而不是从最后一个字符到第一个字符。此外,您的空值检查应该是第一个,长度检查是第二个。
-
int lastIndexOf(int char) docs.oracle.com/javase/6/docs/api/java/lang/…> 采用 unicode 字符值。因为这是递归的作业。我绝对不能用那种方法。