簡體   English   中英

Java String索引越界混亂

[英]Java String index out of bounds confusion

假設我有一個

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

為什么?

此方法Javadocs狀態為:

子字符串從指定的beginIndex開始,並擴展到索引endIndex-1處的字符。

拋出:

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

length的結束索引可以,但length + 1則不行。

根據文檔

public String substring(int beginIndex, int endIndex)

子字符串從指定的beginIndex開始,並擴展到索引endIndex - 1處的字符。

IndexOutOfBoundsException如果beginIndex為負,或者endIndex大於此String對象的長度,或者beginIndex大於endIndex

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

因為子字符串以endIndex-1結尾。

substring(0,4)不考慮0到4。它考慮0到3。第二個索引始終減去1。在第二種情況下,temp [4]超出范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM