【问题标题】:Java lastIndexOf always return -1 if the character is space and fromIndex is set如果字符是空格并且设置了 fromIndex,Java lastIndexOf 总是返回 -1
【发布时间】:2017-06-27 08:58:10
【问题描述】:

测试代码

public class HelloWorld{
     public static void main(String []args){
        System.out.println("Hello World".lastIndexOf(' '));
        System.out.println("Hello World".lastIndexOf(' ', 1));
        System.out.println("Hello World".lastIndexOf('e'));
        System.out.println("Hello World".lastIndexOf('e', 1));
     }
}

结果

5
-1
1
1

我预计第二个结果是 5,但它是 -1。怎么可能第一个是对的,第二个是错的?

【问题讨论】:

  • Checkout 文档:@return 在此对象表示的 * 字符序列中最后一次出现的字符的索引,该字符小于或等于 {@code fromIndex} 或 {@code - 1} * 如果字符在该点之前没有出现。
  • 来自 javadoc :“如果在此字符串 在或之前位置 fromIndex 中没有出现此类字符,则返回 -1。” .
  • 谢谢各位。我知道没有找到-1,但我没有注意到从右到左。名为 fromIndex 的变量让我感到困惑,我假设它搜索从 fromIndex 开始的子字符串。

标签: java string lastindexof


【解决方案1】:

lastIndexOf() 从右到左,所以当它从索引 1(第二个字符,即 'e')开始时,它没有找到空格(索引为 5)。

【讨论】:

    【解决方案2】:

    最简单的方法

    lastIndexOf(int ch, int fromIndex) 仅当它出现在 fromIndex 或之前返回 ch 的索引,否则返回 -1。

    System.out.println("Hello World".lastIndexOf(' ', 3));
    

    返回 -1。

    System.out.println("He llo World".lastIndexOf(' ', 3));
    

    返回 2。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-16
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      相关资源
      最近更新 更多