截取字符串的方法subString详解
public class demo {
public static void main(String[] args) {
String str="123456789";
System.out.println(str.substring(1, 3)); //23 包头不包尾 substring(int beginIndex, int endIndex) 数组下标
}
}
从代码中可以看出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);
}
源码中的beginIndex,和endIndex就是这两个形参,两个形参代表的含义是下标(从0开始),就举上面的数字字符串“123456789”为例子,substring(1, 3)的意思就是说:从下标为1的字符开始往后连续数字符串,一共数三个字符串,最后出来的字符串为 2 3 4,但是最后的结果不包括最后一个字符,简而言之就是 包头不包尾,组后的结果也是 2 3。