Java 11中lastIndexOf方法的用法及输出结果解析咨询
解析Java 11中String.lastIndexOf()的行为
先给你理清楚String.lastIndexOf(String str, int fromIndex)的核心逻辑,这是理解所有结果的关键:
这个方法会从
fromIndex指定的位置开始,向左(往字符串开头方向)搜索,返回子串str最后一次出现的起始索引。注意两个核心规则:
- 子串必须完全匹配,且匹配的起始位置必须 ≤
fromIndex(因为是向左找,起始位置不能在fromIndex的右边);- 如果
fromIndex < 0,直接返回-1(没有合法的搜索起始范围);如果fromIndex ≥ 字符串长度,就等价于调用无参数的lastIndexOf(str)(从字符串末尾开始找)。
先明确你的测试字符串"this is how"的字符索引对应关系:
索引: 0:t, 1:h, 2:i, 3:s, 4:空格, 5:i, 6:s, 7:空格, 8:h, 9:o, 10:w
格式化后的测试代码:
public class Test2{ public static void main(String[] args) { String str="this is how"; int a0=str.lastIndexOf("is"); int a=str.lastIndexOf("is",0); int b=str.lastIndexOf("is",1); int c=str.lastIndexOf("is",2); int d=str.lastIndexOf("is",3); int e=str.lastIndexOf("is",4); int f=str.lastIndexOf("is",5); int b1=str.lastIndexOf("is",-1); int c1=str.lastIndexOf("is",-2); int d1=str.lastIndexOf("is",-3); int e1=str.lastIndexOf("is",-4); int f1=str.lastIndexOf("is",-5); System.out.println("Last index of from index 0 "+a0); System.out.println("Last index of from index 0 "+a); System.out.println("Last index of from index 1 "+b); System.out.println("Last index of from index 2 "+c); System.out.println("Last index of from index 3 "+d); System.out.println("Last index of from index 4 "+a); // 这里有个小错误:应该输出e,你写成a了 System.out.println("Last index of from index 5 "+f); System.out.println("Last index of from index -1 "+b1); System.out.println("Last index of from index -2 "+c1); System.out.println("Last index of from index -3 "+d1); System.out.println("Last index of from index -4 "+e1); System.out.println("Last index of from index -5 "+f1); } }
逐个解析运行结果:
- a0 = str.lastIndexOf("is"):无参数版本,从字符串末尾开始找,最后一次出现"is"是在索引5(i在5,s在6),所以返回
5,和结果一致。 - a = str.lastIndexOf("is", 0):从索引0向左找(其实就是只看索引0的位置),"is"长度是2,起始位置0的话,字符0是
t、1是h,不匹配,返回-1。 - b = str.lastIndexOf("is", 1):从索引1向左找,可能的起始位置是0和1,起始0是
th、起始1是hi,都不匹配"is",返回-1。 - c = str.lastIndexOf("is", 2):从索引2向左找,起始位置2的字符是
i,下一个字符3是s,正好匹配"is",返回2。 - d = str.lastIndexOf("is", 3):从索引3向左找,仍然能找到起始位置2的"is"(起始位置2 ≤ 3),返回
2。 - 关于"Last index of from index 4"的输出:你代码里写错了,应该输出
e但写成了a,所以显示-1。实际调用str.lastIndexOf("is",4)应该返回2(起始位置2 ≤4,匹配有效)。 - f = str.lastIndexOf("is",5):从索引5向左找,这里有两个匹配项:起始2和起始5,取最右边的那个(因为是lastIndexOf,向左找时最后遇到的是5),所以返回
5。 - 负数参数(-1到-5):根据规则,只要
fromIndex <0,直接返回-1,所以所有负数参数的结果都是-1,和你的运行结果一致。
内容的提问来源于stack exchange,提问作者alex K
相关产品推荐
相关产品推荐

