在Java中我使用的substring()方法,我不知道为什么它不会抛出"out of index"错误.
该字符串的abcde索引从0开始到4,但该substring()方法将startIndex和endIndex作为参数,基于我可以调用foo.substring(0)并获取"abcde"的事实.
那么为什么子串(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));
Run Code Online (Sandbox Code Playgroud)
此代码输出:
abcde
bcde
cde
de
e
//foo.substring(5) output nothing here, isn't this out of range?
Run Code Online (Sandbox Code Playgroud)
当我用6替换5时:
foo.substring(6)
Run Code Online (Sandbox Code Playgroud)
然后我得到错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1
Run Code Online (Sandbox Code Playgroud) 这可能有一个非常明显的答案,但是我刚刚开始学习Java并发现了这一点。
说我们有
String x = "apple";
Run Code Online (Sandbox Code Playgroud)
为什么x.substring(5)返回"",并在x.substring(6)引发IndexOutOfBounds异常时为空字符串?是否可以在每个字符串后面附加某种空字符串?只是不确定它是如何工作的。
谢谢!