StringBuffer和String类的区别是StringBuffer中的数组有缓冲,所以不需要每次进行插入操作都重新申请数组,提高了空间利用效率。这里实现了一些StringBuffer的基本操作(几个构造方法,查入和删除操作)。
public class MyStringBuffer implements Serializable{
private char value[]; //字符数组
private int n; //字符个数
public MyStringBuffer(int capacity) {
this.value=new char[capacity];
this.n=0;
}
public MyStringBuffer() {
this(16);
}
public MyStringBuffer(String str){
this(str.length()+16);
this.n=str.length();
for(int i=0;i<n;i++)value[i]=str.charAt(i);
}
public int length(){ //字符串长度
return n;
}
public int capacity(){ //返回储存长度
return this.value.length;
}
public synchronized String toString(){
return new String(this.value,0,n);
}
public synchronized char charAt(int i){
return value[i];
}
public void setCharAt(int i,char ch){
value[i]=ch;
}
public synchronized MyStringBuffer insert(int i,String str){ //在第i位插入str
if(i>=0&&i<=n){ //查询数据是否合法
if(str==null)
str="null";
char[] temp=this.value; //中间变量
if(n+str.length()>value.length){ //如果数组长度不够,则需要继续开辟
value=new char[value.length+str.length()+16];
for(int j=0;j<i;j++) //开辟后把原来的值附上
value[j]=temp[j];
}
//这里要注意的一点是要先添加后面的元素在插入中间的元素,否则中间的元素会损失
for(int j=0;j<n-i;j++) //先添加后面的元素
value[j+i+str.length()]=temp[i+j];
for(int j=0;j<str.length();j++) //然后添加插入元素
value[j+i]=str.charAt(j);
n+=str.length();
return this;
}
else throw new StringIndexOutOfBoundsException("i="+i);
}
public synchronized MyStringBuffer insert(int i,MyStringBuffer sbuf){
return this.insert(i,sbuf.toString());
}
public synchronized MyStringBuffer append(String str){
return this.insert(n, str);
}
public synchronized MyStringBuffer delete(int begin,int end){ //删除从begin到end的元素
if(begin>=0&&begin<n&&begin<end){
if(end>n) //end超长容错
end=n;
for(int i=0;i<=n-end;i++)
value[begin+i]=value[end+i];
n-=end-begin;
return this;
}
else throw new StringIndexOutOfBoundsException("begin="+begin+",end="+end+",end-begin="+(end-begin));
}
}
然后写一个测试类:
public class Test {
public static void main(String[] args) {
MyStringBuffer str=new MyStringBuffer("abcd");
System.out.println(str.toString());
str.append("efg");
System.out.println(str.toString());
str.insert(5,"uuu");
System.out.println(str.toString());
str.delete(1,3);
System.out.println(str.toString());
str.append("123456789abcdefghijk");
System.out.println(str.toString());
}
}
测试结果:
abcd
abcdefg
abcdeuuufg
adeuuufg
adeuuufg123456789abcdefghijk
并没有发现什么错误,应该还可以把,如果哪里错了还请大佬们指点。
参考书籍《数据结构(JAVA版)》第四版。