System.out.println("----"+"".substring(1).length());//question
System.out.println("----"+"1".substring(1).length());第一个出现错误是肯定的,我想了解为什么第二个不报错呢输出来的时候什么都没有,为什么,原因
System.out.println("----"+"1".substring(1).length());第一个出现错误是肯定的,我想了解为什么第二个不报错呢输出来的时候什么都没有,为什么,原因
public String substring(int beginIndex)返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。
示例: "unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" (an empty string)
参数:
beginIndex - 起始索引(包括)。
返回:
指定的子字符串。
抛出:
IndexOutOfBoundsException - 如果 beginIndex 为负或大于此 String 对象的长度。
要大于长度才抛错误
//因为 String index out of range: -1 ,"" -- 空串 长度为0,而你的substring截取的index从1开始 System.out.println("----"+"1".substring(1).length());
//你从第一个字符而不是第0个字符开始截取,也就是什么都没截取到,返回空串 相当于
System.out.println("----"+"".legth());
//当然不会报错
“1”有一个元素,刚好满足
public String substring(int beginIndex) {
return substring(beginIndex, count);
}public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
第二句执行时 打印 ----0。 // "1".substring(1).length() 为 0
这个是"----"字符串和 "".substring(1).length()) ,而“”是空的没有索引为1的子串所以报错啊。
你要将"----"+"".substring(1).length() 分成 "----" 和 "".substring(1).length())两个字符串来看待System.out.println("----"+"1".substring(1).length());
只有beginindex> length在报错;beginindex= length,得到空串
就是----
就像是null一样