2014-03-29 161 views
2

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

+0

's.substrin g(s.length())'是愚蠢但是有效的 – 2014-03-29 11:17:37

+4

*“我认为当我使用s.substring(5)时,它应该给我错误,而不是”* - 不要依靠你的直觉。阅读javadocs。他们说不应该。 –

回答

7

因为endIndex是排他性的,如documentation中所述。

IndexOutOfBoundsException - 如果将beginIndex为负,或者endIndex的 比该字符串对象的长度大,或beginIndex 大于endIndex。


当我用s.substring(5)我想,这应该给我的错误,而它 没有

为什么它会是什么?

返回一个新字符串,该字符串是该字符串的子字符串。子字符串 以指定索引处的字符开头,并扩展到该字符串的 结尾。

由于beginIndex是(你的情况5)比endIndex没有较大的,这是完全有效的。你只会得到一个空字符串。

如果你看一下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,5);

当你调用s.substring(5,5);,它返回一个空字符串,因为你调用构造函数(这是私人包)为0的count值(count代表字符的字符串数):

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

但它没有索引== 5。但我可以使用s.substring(5)?为什么 – user3382017

+0

@ user3382017's.substring(5);'相当于's.substring(5,s.length());'s.substring(5) ,5);'为“你好”。 –

4

因为substring被定义为这样的,你可以在the Javadoc of String.substring

抛出IndexOutOfBoundsException异常发现,如果将beginIndex为负, 或endIndex是大于此String对象的长度或 beginIndex大于endIndex。

这是非常有用在许多情况下,你总是可以创建一个在一个字符串的字符之后开始一子。

由于endIndex可以是串的长度,及beginIndex可以大如endIndex(但不大于),它也还可以用于beginIndex为等于该字符串的长度。

+1

+1。你刚刚教了我一些东西。 minIndex可以等于长度。我从来没有做过,所以我认为这是非法的。 – aliteralmind

1

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

...
IndexOutOfBoundsException - 如果的beginIndex为负或大于这个字符串对象的长度大。
...

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

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

相关问题