2016-02-26 117 views
0

的假設我有一個Java的String索引越界混淆

String temp = "abcd"; 

System.out.println(temp.substring(0,4)); // out of bound, no error 
System.out.println(temp.substring(0,5)); // out of bound, error 

爲什麼?

+0

的第二個參數是endIndex的,但最後指數是3 – KKKK

+0

沒必要重複,但是這可能會感興趣:http://stackoverflow.com/a/33600969/1393766 – Pshemo

回答

3

Javadocs for this method狀態:

的串開始在指定的beginIndex和延伸到字符索引endIndex - 1的

拋出:

IndexOutOfBoundsException - 如果將beginIndex是負數或endIndex大於此String對象的長度,或者beginIndex大於endIndex。

結束索引length可以,但length + 1不是。

+0

如果鍵入的System.out.println(TEMP .substring(4,4));爲什麼-1沒有出現? – KKKK

+0

@KKKK爲什麼會出現'-1'?這應該打印一個空字符串,這將不可見。 – rgettman

0

因爲子字符串在endIndex-1處結束。

1

根據docs

public String substring(int beginIndex, int endIndex)

的串開始在指定的beginIndex並延伸到字符索引endIndex - 1

IndexOutOfBoundsException - 如果beginIndex爲負,或者endIndex比該字符串對象的長度大,或beginIndexendIndex大。

由於System.out.println(temp.substring(0,5));其中5>字符串的長度(abcd),因此是例外。

0

子串(0,4)不考慮0到4.它認爲0到3.第二個索引總是減1.在你的第二種情況下temp [4]超出範圍。