问题描述
在Java中我使用的是 substring()
方法,我不确定为什么它没有抛出out of index错误。
In Java I am using the substring()
method and I'm not sure why it is not throwing an "out of index" error.
字符串 abcde
索引从0开始到4,但 substring()
方法将startIndex和endIndex作为参数,基于我可以调用foo.substring(0)并获取abcde这一事实。
The string abcde
has index start from 0 to 4, but the substring()
method takes startIndex and endIndex as arguments based on the fact that I can call foo.substring(0) and get "abcde".
那么为什么子串(5)工作?该指数应该超出范围。解释是什么?
Then why does substring(5) work? That index should be out of range. What is the explanation?
/*
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
推荐答案
根据,substring在启动索引时抛出错误大于字符串的 Length 。
According to the Java API doc, substring throws an error when the start index is greater than the Length of the String.
事实上,他们举了一个像你的例子:
In fact, they give an example much like yours:
"emptiness".substring(9) returns "" (an empty string)
我想这意味着最好考虑一个Java String如下所示,其中索引包含在 |
中:
I guess this means it is best to think of a Java String as the following, where an index is wrapped in |
:
|0| A |1| B |2| C |3| D |4| E |5|
这就是说字符串同时包含起始和结束索引。
Which is to say a string has both a start and end index.
这篇关于为何“超出范围”没有为'substring(startIndex,endIndex)'抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!