substring(int)方法神奇地不会抛出StringIndexOutOfBoundsException

时间:2014-07-23 11:47:33

标签: java

为什么"a".substring(1)不是throw StringIndexOutOfBoundsException,而对于> = 2的索引呢?这真的很有趣。

提前致谢!

6 个答案:

答案 0 :(得分:5)

您将在源代码中获得答案:

 public String substring(int beginIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        int subLen = value.length - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
    }

其中value.length将在你的条件中得到1

int subLen = value.length - beginIndex; 

会变成: int subLen = 1 - 1; 和subLen将为0,因此if (subLen < 0) {将为false并且不会抛出异常:)

答案 1 :(得分:2)

Behaves as specified in the JavaDoc.

  

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

另外,来自JavaDoc中的示例:

  

"emptiness".substring(9)返回""(空字符串)

因此,"a".substring(1)会返回一个空字符串。

答案 2 :(得分:1)

因为你得到一个空字符串,即""

public static void main(String[] args) {
System.out.println("a".substring(1).equals("")); // substring --> from index 1 upto length of "a" (which is also 1)

}

O / P:

true

当int参数大于String的长度时,得到StringIndexOutOfBoundsException

示例:

System.out.println("a".substring(2).equals("")); // throws StringIndexOutOfBoundsException

答案 3 :(得分:1)

a.substring(1)返回一个空字符串,这就是为什么它不会引发异常,如this问题中所述。如果n大于字符串的长度,则String.substring(n)才会失败。

答案 4 :(得分:1)

看看substring()做了什么。

 public String substring(int beginIndex) {
    if (beginIndex < 0) {
        throw new StringIndexOutOfBoundsException(beginIndex);
    }
    int subLen = value.length - beginIndex;
    if (subLen < 0) {
        throw new StringIndexOutOfBoundsException(subLen);
    }
    return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}

int subLen = value.length - beginIndex;如果subLen<0异常将抛出。在你的情况下,不会发生。

根据您的情况value.length=1beginIndex=1,然后1-1=0

答案 5 :(得分:0)

public static void main(String[] args) {
System.out.println("a".substring(1).equals("")); 
}

You got that from the source code but one point to think is why java has :

You get StringIndexOutOfBoundsException when the int argument is greater that length of the String.


why not throw exception when int argument is equal to length of string because...

String substring(int fromindex); <-prototype

There is no point of NOT throwing exception for int argument '1' as String length is 1 and you are searching from second index..

can anyone give reason?