return lastIndexOf(str, value.length);
}
public int lastIndexOf(String str, int fromIndex) {
return lastIndexOf(value, 0, value.length,
str.value, 0, str.value.length, fromIndex);
}
static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
String target, int fromIndex) {
return lastIndexOf(source, sourceOffset, sourceCount,
target.value, 0, target.value.length,
fromIndex);
}
static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount,
int fromIndex) {
/*
* Check arguments; return immediately where possible. For
* consistency, don't check for null str.
*/
int rightIndex = sourceCount - targetCount;
if (fromIndex < 0) {
return -1;
}
if (fromIndex > rightIndex) {
fromIndex = rightIndex;
}
/* Empty string always matches. */
if (targetCount == 0) {
return fromIndex;
}
int strLastIndex = targetOffset + targetCount - 1;
char strLastChar = target[strLastIndex];
int min = sourceOffset + targetCount - 1;
int i = min + fromIndex;
startSearchForLastChar:
while (true) {
while (i >= min && source[i] != strLastChar) {
i--;
}
if (i < min) {
return -1;
}
int j = i - 1;
int start = j - (targetCount - 1);
int k = strLastIndex - 1;
while (j > start) {
if (source[j--] != target[k--]) {
i--;
continue startSearchForLastChar;
}
}
return start - sourceOffset + 1;
}
}
这四个方法一起来看,和上一篇类似,这四个方法是在返回参数字符串最后出现的下标。
第一个方法就一个参数,也就是要查询的字符串,然后调用第二个方法把参数字符串,和本字符串value的长度传过去。
第二个方法调用第四个方法,传入的参数分别是本字符串的value数组、本字符串的起始下标0、本字符串的长度、参数字符串的value数组、参数字符串的起始下标0、参数字符串的长度以及本字符串的搜索起始下标。
第四个方法先计算两个字符串的长度之差,用rightIndex变量表示。判断如果本字符串起始搜索下标小于0,则返回-1,如果起始搜索下标fromIndex大于rightIndex,则将fromIndex赋值为rightIndex。假设源字符串长度为10,参数字符串长度为3,那么要搜索的话,从源字符串下标为10-3的地方开始搜索才有意义,这就是fromIndex和rightIndex的意义所在。然后判断参数字符串的长度是否为0,为0的话返回fromIndex。
然后计算参数字符串最后一位的下标,用参数字符串起始下标加上参数字符串长度减一。然后获得参数字符串最后一位的字符strLastChar。然后创建变量min,赋值为本字符串起始下标加上参数字符串长度减一,然后定义变量i,用min加上fromIndex。
接下来进入一个名为startSearchForLastChar的while循环,这个循环的目的是,从源字符串的fromIndex处开始搜索,源字符串的value数组下标逐渐左移,直到min处为止,从0到min就是参数字符串的长度,如果到了min处还没匹配到参数字符串那么min之前的数组元素就没有必要再遍历了。
一旦发现源字符串i下标的元素和strLastChar相等,就退出第一个嵌套while循环,这个嵌套while循环就在不停比较源字符串中的第i个元素和strLastChar是否相等,如果不等i递减。举个例子,如果从第一个方法调用的话,i初始值实际就是targetCount - 1+sourceCount - targetCount,也就是源字符串最后一个元素,因为targetOffset为0,且fromIndex为源字符串长度肯定大于rightIndex,所以fromIndex肯定会赋值为rightIndex,也就是两个字符串长度之差。
判断如果i小于min,那么返回-1。
然后将i-1赋给变量j,然后变量start其实就是i-targetCount,这个start就是i的位置开始向左数targetCount个元素,就是判断i左边的元素集合是不是参数字符串。
变量k就是参数字符串的倒数第二个元素。
然后进入第二个嵌套的while循环,将源字符串j开始的位置和参数字符串从倒数第二个元素开始进行比较,然后两个字符串的下标都向左移,挨个比较,一旦比较失败,i递减,跳出外层while循环。
如果一直匹配的话,结束循环返回start-sourceOffet+1,如果从第一个方法进来的话就是start+1,也就是i-targetCount+1,就是找到的和参数最后一个字符相等的源字符串i处元素向左移动targetCount-1处的元素的下标