字符串子字符串索引可以是字符串的长度

这是一个Java字符串问题。 我使用substring(beginindex)来获取子字符串。 考虑到String s="hello" ,这个字符串的长度是5.但是当我使用s.substring(5)s.substring(5,5) ,编译器没有给我一个错误。 字符串的索引应该是从0到length-1。 为什么它不适用于我的情况? 我认为s.substring(5)应该给我一个错误,但事实并非如此。

因为endIndex是独占的,如文档中所指定的那样。

IndexOutOfBoundsException – 如果beginIndex为负数,或者endIndex大于此String对象的长度,或者beginIndex大于endIndex。


我想当我使用s.substring(5)时,它应该给我错误,而不是

为什么会这样?

返回一个新字符串,该字符串是此字符串的子字符串。 子字符串以指定索引处的字符开头,并延伸到此字符串的末尾。

由于beginIndex不大于endIndex (在你的情况下是5),所以它完全有效。 你将获得一个空字符串。

如果你看一下源代码 :

 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( count表示字符串中的字符数):

 644 String(int offset, int count, char value[]) { 645 this.value = value; 646 this.offset = offset; 647 this.count = count; 648 } 

因为substring是这样定义的,所以你可以在String.substring的Javadoc中找到它

@exception IndexOutOfBoundsException如果beginIndex为负数,或者endIndex 于此String对象的长度 ,或者beginIndex大于endIndex。

在许多情况下,您总是可以创建一个在String中的字符后面开始的子字符串。

因为endIndex可以是字符串的长度,并且beginIndex可以和endIndex一样大(但不能更大),所以beginIndex也可以等于字符串的长度。

在第一种情况下( s.substring(5) ),Oracle文档说


IndexOutOfBoundsException – 如果beginIndex为负或大于此String对象的长度。

在第二种情况下( s.substring(5,5) ),它说


IndexOutOfBoundsException – 如果beginIndex为负数,或者endIndex大于此String对象的长度,或者beginIndex大于endIndex