if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
System.arraycopy(value, index+1, value, index, count-index-1);
count--;
return this;
}
这个方法是删除指定下标的字符。
先判断下标是否越界,否则抛异常。
然后将下标之后的元素拷贝到下标处,count自减一。最后返回本对象。
public AbstractStringBuilder replace(int start, int end, String str) {
if (start < 0)
throw new StringIndexOutOfBoundsException(start);
if (start > count)
throw new StringIndexOutOfBoundsException("start > length()");
if (start > end)
throw new StringIndexOutOfBoundsException("start > end");
if (end > count)
end = count;
int len = str.length();
int newCount = count + len - (end - start);
ensureCapacityInternal(newCount);
System.arraycopy(value, end, value, start + len, count - end);
str.getChars(value, start);
count = newCount;
return this;
}
这个方法是将一个字符串镶嵌在本对象中。
先给value扩容,扩大的容量就是两个字符串之和减去下标之差。
然后将end下标之后的字符复制到start+len下标之后,这样start和end之间就有了len长度的空白,然后将参数填充进去。
最后返回本对象。
public String substring(int start) {
return substring(start, count);
}
public CharSequence subSequence(int start, int end) {
return substring(start, end);
}
public String substring(int start, int end) {
if (start < 0)
throw new StringIndexOutOfBoundsException(start);
if (end > count)
throw new StringIndexOutOfBoundsException(end);
if (start > end)
throw new StringIndexOutOfBoundsException(end - start);
return new String(value, start, end - start);
}
这三个方法一起看,就是截取字符串。这里是返回新字符串。