数据结构-串-StringBuffer基本操作(JAVA)

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版)》第四版。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值