接口
public interface IStringBuffer {
public void append(String str); //追加字符串
public void append(char c); //追加字符
public void insert(int pos,char b); //指定位置插入字符
public void insert(int pos,String b); //指定位置插入字符串
public void delete(int start); //从开始位置删除剩下的
public void delete(int start,int end); //从开始位置删除结束位置-1
public void reverse(); //反转
public int length(); //返回长度
}
实现
package how2j;
public class MyStringBuffer implements IStringBuffer {
// 容量
int capacity = 16;
// 长度
int length = 0;
// 字符数组
char[] value;
// 无参构造方法,初始化 value
public MyStringBuffer() {
value = new char[capacity];
}
// 有参构造方法
public MyStringBuffer(String str) {
this();
if (str == null)
return;
// 扩容
ensureCapacity(str.length());
System.arraycopy(str.toCharArray(), 0, value, 0, str.length());
length = str.length();
}
// 扩容函数
public void ensureCapacity(int minCapacity) {
while (minCapacity > capacity) {
capacity = minCapacity * 2;
char[] newValue = new char[capacity];
System.arraycopy(value, 0, newValue, 0, length);
value = newValue;
}
}
@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 b) {
insert(pos, String.valueOf(b));
}
// pu
@Override
public void insert(int pos, String b) {
// 边界判断
if (pos < 0 || pos > length || b == null)
return;
// 扩容
ensureCapacity(b.length() + length);
char[] cs = b.toCharArray();
// 把要插入的位置腾出来
System.arraycopy(value, pos, value, pos + cs.length, length - pos);
// 插入数据
System.arraycopy(cs, 0, value, pos, cs.length);
length += cs.length;
}
public void delete(int start) {
delete(start, length);
}
public void delete(int start, int end) {
// 边界判断
if (start < 0 || start > length || end < 0 || end > length || start >= end)
return;
// 用后面的数据把要删除部分覆盖
System.arraycopy(value, end, value, start, length - end);
length -= end - start;
}
public void reverse() {
for (int i = 0; i < length / 2; i++) {
char tmp = value[i];
value[i] = value[length - i - 1];
value[length - i - 1] = tmp;
}
}
public int length() {
return length;
}
public String toString() {
return new String(value);
}
public static void main(String[] args) {
MyStringBuffer sb = new MyStringBuffer("there light");
System.out.println(sb);
sb.insert(1, "let ");
System.out.println(sb);
sb.insert(4, "be ");
System.out.println(sb);
sb.insert(0, "God Say:");
System.out.println(sb);
sb.append("!");
System.out.println(sb);
sb.append('?');
System.out.println(sb);
sb.reverse();
System.out.println(sb);
sb.reverse();
System.out.println(sb);
sb.delete(0, 4);
System.out.println(sb);
sb.delete(4);
System.out.println(sb);
}
}