String.substring(String.length)的输出是什么?

时间:2019-04-16 07:03:51

标签: java string

public class Str {

    public static void main(String[] args) {

        String str = "abcde";
        String s = str.substring(str.length());
        System.out.println(s);
    }

}

字符'e'的索引为4,但是我试图获取长度为5的整个字符串。如果执行上述代码,为什么它不抛出IndexOutOfBoundsException

3 个答案:

答案 0 :(得分:5)

String.substring()的JavaDoc指出:

  

[throws] IndexOutOfBoundsException-如果beginIndex为负或大于此String对象的长度。

由于beginIndex等于字符串的长度,因此它是有效值,并且substring()返回一个空字符串。

答案 1 :(得分:1)

空字符串(长度为0的“”)是有效的字符串。这就是您的代码返回的内容。

换句话说,str.substring(str.length()-1);返回字符串“ e”,而str.substring(str.length());返回空字符串。完全有效。

答案 2 :(得分:0)

假设您有一个字符串:

Hello World

这是标记的样子:

H e l l o   W o r l  d
0 1 2 3 4 5 6 7 8 9 10

“ Hello World”的长度为11,因此在这种情况下str.length等于11

现在那里没有索引11,实际上11超出了最后一个索引。那就是为什么您收到IndexOutOfBounds

另外,str.substring(number)从指定的数字一直返回到字符串末尾的子字符串STARTING。

因此str.substring(4)在这种情况下将返回

o World

只是想我应该把它放在这里

相关问题