字符串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
本文由 投稿者 创作,文章地址:https://blog.isoyu.com/archives/java-weishenmesubstringstartindexendindex.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:9 月 19, 2019 at 04:13 上午