String的subString方法源码
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
我们可以看到substring是传进来两个值,一个起始值一个某尾值,前面两个if就是防止传入起始位置小于0和末尾位置大于0的。subLen就是截取的字符长度,然后是校验起始下标是否小于末尾下标。最后是如果传入起始下标为0并且末尾下标为字符串长度的,那么直接返回原字符串,否则就创建一个新字符串。这里注意比如
public static void main(String[] args) {
String str = "123";
String str1 = str.substring(0,2);
System.out.println(str1);
}
最后输出的是"12",因为下标为2的字符不会被截取到
int subLen = endIndex - beginIndex;
endIndex位置的字符并不会被截取。