java为什么代码以这种方式编写字符串中的indexOf()方法。班
我正在读String.class
的源代码
在方法indexOf()
中,我看到了一些我无法理解的东西
下面是来自String.class
源代码的indexOf()
代码片段
/**
* Code shared by String and StringBuffer to do searches. The
* source is the character array being searched, and the target
* is the string being searched for.
*
* @param source the characters being searched.
* @param sourceOffset offset of the source string.
* @param sourceCount count of the source string.
* @param target the characters being searched for.
* @param targetOffset offset of the target string.
* @param targetCount count of the target string.
* @param fromIndex the index to begin searching from.
*/
static int indexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount,
int fromIndex) {
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);
for (int i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (source[i] != first) {
while (++i <= max && source[i] != first);
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = targetOffset + 1; j < end && source[j]
== target[k]; j++, k++);
if (j == end) {
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;
}
我无法理解这里的代码
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
如果source String
是"abcdedefg"
,sourceOffset
是2
,sourceCount
是3
,
我想从中搜索“d”,
为什么我不能从索引4中搜索
/**
*Ps:如果sourceCount
表示整个字符串的长度,为什么不使用source.length
*相反
*/
# 1 楼答案
此方法接受两个字符数组
source
数组是正在搜索的数组target
数组是正在搜索的数组然而,偏移量和计数变量将搜索限制为
source
的子数组和target
的子数组基本上,您是在从
source[sourceOffSet]
到source[sourceOffset+sourceCount-1]
的子数组中搜索由从target[targetOffSet]
到target[targetOffset+targetCount-1]
的子数组中的字符组成的String
这是一个例子。搜索的相关数组为子数组:
然而,通过提供
fromIndex
进一步限制了搜索。从source
子数组的第fromIndex
个索引开始搜索由于
让我们考虑一下你的例子:source
子数组的长度为sourceCount
,如果fromIndex >= sourceCount
,则无法找到target
子数组,因此除非target
子数组为空(即targetCount == 0
),否则返回-1
这些参数意味着您正在源子字符串
"cde"
中搜索从索引4
开始的目标子字符串"d"
。但是,在"cde"
中没有索引4
,因此返回-1
关于你的
正如我所解释的
sourceCount
并不意味着整个source
数组的长度,只是被搜索的子数组的长度请注意,当您调用
someString.indexOf(str,fromIndex)
时,您询问的static
方法将使用以下参数进行调用:在这种情况下
sourceCount
等于source.length
(即从fromIndex
开始搜索整个source
数组)# 2 楼答案
这意味着在搜索索引(
fromIndex
)中,字符串长度(sourceCount
)在末尾之后,然后返回-1
(未找到),除非搜索的字符串是""
,这是“始终找到的”非常具体