[英]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
為什么?
根據文檔 :
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.