谁能帮我看看下面代码的结果
String banner = "One man, One vote";
int subInd1 = banner.lastIndexOf("One", 10);
System.out.println(subInd1);
将会输出什么结果? //请详细解答lastIndexOf("One", 10);
具体是什么意思
从index为10的字符开始找 One 最后一次出现的起始下标吗----------------------------------------------
API查参考
lastIndexOf
public int lastIndexOf(String str,
int fromIndex)从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。返回的整数是最大值 k,它满足:
k <= Math.min(fromIndex, str.length()) && this.startsWith(str, k)
如果不存在这样的 k 值,则返回 -1。 参数:
str - 要搜索的子字符串。
fromIndex - 开始搜索的索引位置。
返回:
最后一次出现的指定子字符串在此字符串中的索引。
----------------------------------------------
最后一个 One 出现在下标 9,10开始不是没有 One 了吗,为什么不是 -1
下标从0开始吗?
String banner = "One man, One vote";
int subInd1 = banner.lastIndexOf("One", 10);
System.out.println(subInd1);
将会输出什么结果? //请详细解答lastIndexOf("One", 10);
具体是什么意思
从index为10的字符开始找 One 最后一次出现的起始下标吗----------------------------------------------
API查参考
lastIndexOf
public int lastIndexOf(String str,
int fromIndex)从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。返回的整数是最大值 k,它满足:
k <= Math.min(fromIndex, str.length()) && this.startsWith(str, k)
如果不存在这样的 k 值,则返回 -1。 参数:
str - 要搜索的子字符串。
fromIndex - 开始搜索的索引位置。
返回:
最后一次出现的指定子字符串在此字符串中的索引。
----------------------------------------------
最后一个 One 出现在下标 9,10开始不是没有 One 了吗,为什么不是 -1
下标从0开始吗?
看看banner.lastIndexOf("One", 7);的结果就明白了:)
0123456789
int subInd1 = banner.lastIndexOf("One", 10);
System.out.println(subInd1);所以你的参数只要大于9即可,结果都是9,但如果小于9的话,结果都是0。测试是验证了。不怕笑话,还是不明白。
-----------------0123456789-------
int subInd1 = banner.lastIndexOf("One", 10);
System.out.println(subInd1);
int fromIndex)从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。'向后搜索' 是指 9->8->1->0
-----------------------------------------------
lastIndexOf
public int lastIndexOf(String str,
int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward(向后地(的), 相反地(的), 追溯, 退步) starting at the specified index. The integer returned is the largest value k such that:
k <= Math.min(fromIndex, str.length()) && this.startsWith(str, k)
If no such value of k exists, then -1 is returned. Parameters:
str - the substring to search for.
fromIndex - the index to start the search from.
Returns:
the index within this string of the last occurrence of the specified substring.