【问题标题】:Java String index out of bounds confusionJava 字符串索引越界混淆
【发布时间】:2016-06-10 07:14:53
【问题描述】:

假设我有一个

String temp = "abcd";

System.out.println(temp.substring(0,4)); // out of bound, no error
System.out.println(temp.substring(0,5)); // out of bound, error

为什么?

【问题讨论】:

标签: java arrays string indexoutofboundsexception


【解决方案1】:

substring(0,4) 不考虑 0 到 4。它考虑 0 到 3。第二个索引总是减去 1。在第二种情况下,temp[4] 超出范围。

【讨论】:

    【解决方案2】:

    根据docs

    public String substring(int beginIndex, int endIndex)

    子字符串从指定的beginIndex 开始并延伸到索引endIndex - 1 处的字符。

    IndexOutOfBoundsException - 如果beginIndex 为负数,或者endIndex 大于此String 对象的长度,或者beginIndex 大于endIndex

    由于System.out.println(temp.substring(0,5)); where 5 > 字符串长度 (abcd),因此例外。

    【讨论】:

      【解决方案3】:

      Javadocs for this method 状态:

      子字符串从指定的 beginIndex 开始并延伸到索引 endIndex - 1 处的字符。

      投掷:

      IndexOutOfBoundsException - 如果 beginIndex 为负数,或者 endIndex 大于此 String 对象的长度,或者 beginIndex 大于 endIndex。

      结束索引length 可以,但length + 1 不行。

      【讨论】:

      • 如果我输入 System.out.println(temp.substring(4, 4));为什么 -1 没有出现?
      • @KKKK 为什么-1 会出现?那应该打印一个空字符串,它是不可见的。
      【解决方案4】:

      因为子字符串在 endIndex-1 结束。

      【讨论】:

        猜你喜欢
        • 2012-12-01
        • 2019-08-01
        • 2013-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-22
        • 2011-12-13
        • 1970-01-01
        相关资源
        最近更新 更多