在Java中我使用的是substring()
方法,我不确定为什么它没有抛出“索引外”错误。
字符串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?
当我用 6 替换 5 时:
foo.substring(6)
然后我得到错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1
根据Java API 文档,当起始索引大于子字符串时,子字符串会抛出错误Length字符串的。
IndexOutOfBoundsException - 如果
beginIndex 为负数或大于
此 String 对象的长度。
事实上,他们举了一个很像你的例子:
"emptiness".substring(9) returns "" (an empty string)
我想这意味着最好将 Java 字符串视为如下所示,其中索引包含在|
:
|0| A |1| B |2| C |3| D |4| E |5|
也就是说,一个字符串同时具有开始索引和结束索引。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)