当索引1中没有元素时,为什么不跟随java代码抛出java.lang.StringIndexOutOfBoundsException?
String str="x"; System.out.println(str.substring(1));
来自Javadoc:
String java.lang.String.substring(int beginIndex)
:返回一个新字符串,它是该字符串的子字符串。 子字符串以指定索引处的字符开头,并延伸到此字符串的末尾。
看看JavaDoc ,并特别注意“空虚”的例子:
Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. Examples: "unhappy".substring(2) returns "happy" "Harbison".substring(3) returns "bison" "emptiness".substring(9) returns "" (an empty string) Parameters: beginIndex the beginning index, inclusive. Returns: the specified substring. Throws: IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object
if beginIndex is negative or larger than the length of this String object
则抛出exception; 在您的情况下,beginIndex等于字符串的长度,而不是更大。