简体   繁体   English

Java String索引越界混乱

[英]Java String index out of bounds confusion

Suppose I have a 假设我有一个

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

Why? 为什么?

The Javadocs for this method state: 此方法Javadocs状态为:

The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. 子字符串从指定的beginIndex开始,并扩展到索引endIndex-1处的字符。

Throws: 抛出:

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex. IndexOutOfBoundsException-如果beginIndex为负,或者endIndex大于此String对象的长度,或者beginIndex大于endIndex。

An end index of length is ok, but length + 1 is not. length的结束索引可以,但length + 1则不行。

According to docs : 根据文档

public String substring(int beginIndex, int endIndex)

The substring begins at the specified beginIndex and extends to the character at index endIndex - 1 . 子字符串从指定的beginIndex开始,并扩展到索引endIndex - 1处的字符。

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex . IndexOutOfBoundsException如果beginIndex为负,或者endIndex大于此String对象的长度,或者beginIndex大于endIndex

Since System.out.println(temp.substring(0,5)); 由于System.out.println(temp.substring(0,5)); where 5 > length of string ( abcd ), hence the exception. 其中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