字符串a =“x”;那么String x = a.substring(1)不会出现像indexOutOfRange这样的错误吗? [重复]

问题描述 投票:-4回答:2

这个问题在这里已有答案:

我感到很困惑。我想使用str.substring(1),str必须至少有2个字符,否则应该有绑定索引。但是当我输入时,Java不会给出任何错误。为什么?

java string
2个回答
1
投票

阅读Javadoc:

String java.lang.String.substring(int beginIndex)

返回一个字符串,该字符串是此字符串的子字符串。子字符串以指定索引处的字符开头,并延伸到此字符串的末尾。

抛出:

IndexOutOfBoundsException - 如果beginIndex为负或大于此String对象的长度。

你的beginIndex等于String的长度,因此不会抛出任何异常并返回空的String


0
投票

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-

IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

使索引等于长度以返回空字符串是合法的。

© www.soinside.com 2019 - 2024. All rights reserved.