2014-03-29 101 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
...

相關問題