这是一个Java字符串问题。我使用substring(beginindex)
来获取子字符串。
考虑String s="hello"
,此字符串的长度为5.但是当我使用s.substring(5)
或s.substring(5,5)
时,编译器没有给我一个错误。字符串的索引应该是从0到length-1。
为什么它不适用于我的案子?我认为s.substring(5)
应该给我一个错误,但它没有。
答案 0 :(得分:7)
因为endIndex
是独占的,正如documentation中指定的那样。
IndexOutOfBoundsException - 如果beginIndex为负数或endIndex 大于此String对象的长度,或者beginIndex是 大于endIndex。
我认为当我使用s.substring(5)时,它应该给我错误 没'吨
为什么会这样?
返回一个新字符串,该字符串是此字符串的子字符串。子串 从指定索引处的字符开始并扩展到 这个字符串的结尾。
由于beginIndex
不大于endIndex
(在您的情况下为5),因此它完全有效。你将获得一个空字符串。
如果你看source code:
1915 public String substring(int beginIndex) {
1916 return substring(beginIndex, count);
1917 }
....
1941 public String substring(int beginIndex, int endIndex) {
1942 if (beginIndex < 0) {
1943 throw new StringIndexOutOfBoundsException(beginIndex);
1944 }
1945 if (endIndex > count) {
1946 throw new StringIndexOutOfBoundsException(endIndex);
1947 }
1948 if (beginIndex > endIndex) {
1949 throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1950 }
1951 return ((beginIndex == 0) && (endIndex == count)) ? this :
1952 new String(offset + beginIndex, endIndex - beginIndex, value);
1953 }
因此,s.substring(5);
相当于s.substring(5, s.length());
,在您的情况下为s.substring(5,5);
。
当您调用s.substring(5,5);
时,它会返回一个空字符串,因为您正在调用count
值为0的构造函数(私有包)({{1表示字符串中的字符数):
count
答案 1 :(得分:4)
由于substring
是这样定义的,您可以在the Javadoc of String.substring
@exception IndexOutOfBoundsException如果beginIndex为负数, 或 endIndex 大于此String对象的长度,或 beginIndex大于endIndex。
在许多情况下,您总是可以创建一个子字符串,该字符串在字符串中的字符后启动。
因为endIndex
可以是字符串的长度,而beginIndex
可以与endIndex
一样大(但不是更大),beginIndex
也可以等于字符串的长度。
答案 2 :(得分:1)
在第一种情况下(s.substring(5)
),Oracle文档说
...
IndexOutOfBoundsException - 如果 beginIndex 为负或大于此String对象的长度。
...
在第二种情况下(s.substring(5,5)
),它说
...
IndexOutOfBoundsException - 如果 beginIndex 为负数,或者endIndex大于此String对象的长度,或者beginIndex大于endIndex
...