一、类
public final class String:final关键字说明String类不能被修改(不能被其他类继承和重写)
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
二、方法
1、subString(int beginIndex, int endIndex):截取子字符串
1) 第一层方法
public String substring(int beginIndex, int endIndex) {
// beginIndex校验不能小于0
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
// endIndex校验不能>数组长度
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);
}
2) 调用String的有参构造方法
public String(char value[], int offset, int count) {
// beginIndex不能小于0
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
// count = endIndex-beginIndex <=0的情况
if (count <= 0) {
// count小于0,抛出异常
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// count = 0时,输出空字符串
if (offset <= value.length) {
this.value = "".value;
return;
}
}
// endIndex > value.length长度时抛出异常
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
// 执行数组复制
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
3) 调用Arrays.copyOfRange方法实现复制数组中元素到另外一个char数组中
public static char[] copyOfRange(char[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
// 声明一个char数组,用来装载截取的子字符串
char[] copy = new char[newLength];
// 核心代码,最终通过它实现将char原始数组中的元素复制到另外一个char数组中
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
未完待续~