Java - String的lastIndexOf(String str, int fromIndex)方法问题

最近在使用String中的lastIndexOf(String str, int fromIndex)方法的时候,发现有时候的返回值与我们想要的结果不一样,在这里进行记录。

问题:返回String str = "helloworld"中“llo”字符存在的索引位置,使用lastIndexOf()或者Indexof()方法。

public void test1() {
	String str = "helloworld";
    // 1. int indexOf(String str): 返回指定子字符串在此字符串中第一次出现处的索引
    int i1 = str.indexOf("llo");
    int i2 = str.indexOf("lloo"); // 如果找不到,则返回-1
    System.out.println(i1);       // 2
    System.out.println(i2);       // -1
    System.out.println("--------------------------------");

    // 2. int indexOf(String str, int fromIndex): 返回指定子字符串在此字符中第一此出现处的索引,从指定的索引开始
    int i3 = str.indexOf("llo", 2);
    int i4 = str.indexOf("llo", 4); // 如果找不到,则返回-1
    System.out.println(i3); // 2
    System.out.println(i4); // -1
    System.out.println("--------------------------------");

    // 3. int lastIndexOf(String str): 返回指定子字符串在此字符串最后边出现处的索引
    int i5 = str.lastIndexOf("llo");
    System.out.println(i5); // 2
    System.out.println("--------------------------------");

    // 4. int lastIndexOf(String str, int fromIndex): 返回指定子字符串在此字符串中最后一次出现处的索引,**从指定的索引开始返向(左)搜索**。
    String str2 = "hellorworld";
    int i6 = str2.lastIndexOf("or", 6);
    int i7 = str2.lastIndexOf("or", 3);
    // 输出: str = helloworld, str.substr(0, 4) = hell
    System.out.println("str = " + str2 + ", str.sunstr(0, 4) = " + str2.substring(0, 4));
    int i8 = str2.substring(0, 4).lastIndexOf("llo", 3);
    System.out.println(i6); // 4
    System.out.println(i7); // -1
    System.out.println(i8); // -1
    System.out.println("--------------------------------");

    System.out.println(new String("helloworld").lastIndexOf("llo", 0)); // -1
    System.out.println(new String("helloworld").lastIndexOf("llo", 1)); // -1
    // note: 下面会输出2,可能是因为此时我们从索引2开始,helloworld的索引2为l,与"llo"的第一个元素相同,此时会继续往后(右边)寻找,知道匹配完成
    System.out.println(new String("helloworld").lastIndexOf("llo", 2)); // 2
    System.out.println(new String("hellworllod").lastIndexOf("llo", 3)); // -1
    System.out.println(new String("helloworllod").lastIndexOf("llo", 3)); // 2
}

note: 我们可以观察到在new String("helloworld").lastIndexOf("llo", 2))中将会返回2,而按照我们正常的思路,此时程序将会从索引2开始向左查找,应该是返回-1。这里我的解释是:此时我们从索引2开始,helloworld的索引2为l,与"llo"的第一个元素相同,此时会继续往后(右边)寻找,直到匹配完成或找不到后会继续向左查找

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值