在Java语言中,我使用的是substring()
方法,我不确定它为什么没有抛出"out of index“错误。
字符串abcde
的索引从0到4,但是substring()
方法使用startIndex和endIndex作为参数,因为我可以调用foo.substring(0)并获取"abcde“。
那么为什么substring(5)可以工作呢?该索引应该超出范围。解释是什么?
/*
1234
abcde
*/
String foo = "abcde";
System.out.println(foo.substring(0));
System.out.println(foo.substring(1));
System.out.println(foo.substring(2));
System.out.println(foo.substring(3));
System.out.println(foo.substring(4));
System.out.println(foo.substring(5));
此代码输出:
abcde
bcde
cde
de
e
//foo.substring(5) output nothing here, isn't this out of range?
当我将5替换为6时:
foo.substring(6)
然后我得到了错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1
https://stackoverflow.com/questions/3233379
复制相似问题