[英]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.