1.String.substring()方法
private final char value[];
substring(beginIndex,endIndex) 方法返回字符串的子字符串。
-
beginIndex -- 起始索引(包括), 索引从 0 开始。
-
endIndex -- 结束索引(不包括)。
再JDK1.7+中实际是重新创建了一个字符数组
String.substring()有两个方法
实现方法
判断beginIndex和endIndex是否合法,否则抛出异常
通过new String(value, beginIndex, subLen)方法复制字符串
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);
}
this.value = Arrays.copyOfRange(value, offset, offset+count);
复制一个数组从offset到offset+count
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= value.length) {
this.value = "".value;
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
2.String.charAt()方法
返回字符串指定索引处的字符
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}