创建一个自己的MyStringBuffer类
实现与StringBuffer一样的如下方法:
// 追加字符串的方法
public void append(String str);
// 追加字符的方法
public void append(char c);
// 在指定位置插入字符的方法
public void insert(int pos, char c);
// 在指定位置插入字符串的方法
public void insert(int pos, String str);
// 删除字符的方法,删除从指定位置到结束
public void delete(int start);
// 删除字符的方法,从开始位置删除到结束位置-1
public void delete(int start, int end);
// 反转字符串的方法
public void reverse();
// 返回字符串长度的方法
public int length();
/**
* 自己创建的MyStringBuffer类
*
* @author Hzy
*
*/
public class MyStringBuffer implements IMyStringBuffer {
private int capacity = 16;// 定义初始化容量
private int length = 0;// 定义字符串的长度
private char[] value;// 定义字符数组,存储字符串的字符
// 无参构造方法
public MyStringBuffer() {
// 初始化字符数组长度
value = new char[capacity];
}
// 有参构造方法
public MyStringBuffer(String str) {
this();
// 判断传入的字符串是否为空
if (str == null) {
return;
}
// 扩充容量
if (capacity < str.length()) {
capacity = str.length() * 2;
value = new char[capacity];
}
if (capacity >= str.length()) {
System.arraycopy(str.toCharArray(), 0, value, 0, str.length());
}
length = str.length();
}
// 追加字符串的方法
@Override
public void append(String str) {
insert(length, str);
}
// 追加字符的方法
@Override
public void append(char c) {
append(String.valueOf(c));
}
// 在指定位置插入字符的方法
@Override
public void insert(int pos, char c) {
insert(pos, String.valueOf(c));
}
// 在指定位置插入字符串的方法
@Override
public void insert(int pos, String str) {
// 边界条件判断
if (pos < 0) {
return;
}
if (pos > length) {
return;
}
if (str == null) {
return;
}
// 扩充容量
while (length + str.length() > capacity) {
capacity = (int) ((length + str.length()) * 1.5F);
char[] newValue = new char[capacity];
System.arraycopy(value, 0, newValue, 0, length);
value = newValue;
}
char[] c = str.toCharArray();
// 先把已经存在的数据往后移
System.arraycopy(value, pos, value, pos + c.length, length - pos);
// 将要插入的数据插入到指定的位置
System.arraycopy(c, 0, value, pos, c.length);
length = length + c.length;
}
// 删除字符的方法,删除从指定位置到结束
@Override
public void delete(int start) {
delete(start, length);
}
// 删除字符的方法,从开始位置删除到结束位置-1
@Override
public void delete(int start, int end) {
// 边界判断
if (start < 0) {
return;
}
if (start > length) {
return;
}
if (end > length) {
return;
}
if (start >= end) {
return;
}
System.arraycopy(value, end, value, start, length - end);
length -= end - start;
}
// 反转字符串的方法
@Override
public void reverse() {
for (int i = 0; i < length / 2; i++) {
char temp = value[i];
value[i] = value[length - i - 1];
value[length - i - 1] = temp;
}
}
// 返回字符串长度的方法
@Override
public int length() {
return this.length;
}
// 重写toString方法
public String toString() {
char[] realValue = new char[length];
System.arraycopy(value, 0, realValue, 0, length);
return new String(realValue);
}
}