Java源码String类lastIndexOf方法的分析

来源:互联网 发布:python ui automation 编辑:程序博客网 时间:2024/05/16 01:55
Java源码String类lastIndexOf方法的分析
public static int lastIndexOf() {
String str = "abcabcdacc";
char[] source = str.toCharArray();
int sourceOffset = 0;
int sourceCount = str.length();
String targetStr = "ecd";
char[] target = targetStr.toCharArray();
int targetOffset = 0;
int targetCount = targetStr.length();
int fromIndex = str.length();
/*
* 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;
}
//being searched String last index
int strLastIndex = targetOffset + targetCount - 1;
char strLastChar = target[strLastIndex];//last char
int min = sourceOffset + targetCount - 1;//min count
int i = min + fromIndex;//source string array length

startSearchForLastChar:
while (true) {
//开始target[]匹配最后一个字符char,记录最后的位置i
while (i >= min && source[i] != strLastChar) {
i--;
}
if (i < min) {//如果匹配到最后一个字符的index小于target[]的最小长度,直接返回-1
return -1;
}
//否则,最后一个匹配成功。则从倒数第二个开始匹配
int j = i - 1;//source[]中开始匹配的index
//target[]中下一个需要匹配的位置
int start = j - (targetCount - 1);
int k = strLastIndex - 1;

while (j > start) {//循环匹配
char s = source[j--];
char t = target[k--];
if (s != t ) {//不相同,则source中最后一个字符的index i--
   i--;
   continue startSearchForLastChar;
}
}
//匹配到之后,返回对应的index位置
return start - sourceOffset + 1;
}
}
0 0