在Java中我使用substring()方法,我不知道它为什么不抛出“out of index”错误.
字符串abcde的索引从0到4开始,但是substring()方法根据我可以调用foo.substring(0)并获取“abcde”的事实将startIndex和endIndex作为参数.
那么为什么子串(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?
当我用6替换5时:
foo.substring(6)
然后我得到错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1