数据结构变量字符串类(JAVA)
package Chapter3;
import java.io.Serializable;
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 s){
this(s.length()+16);
this.n=s.length();
for (int i=0; i<this.n; i++){
this.value[i]=s.charAt(i);
}
}
public int length(){
return this.n;
}
public int capacity(){
return this.value.length;
}
public synchronized String toString(){
return new String(this.value, 0, this.n);
}
public synchronized char charAt(int i){
if (i < 0){
i=0;
}
else if (i > this.n){
i=this.n;
}
return this.value[i];
}
public void setCharAt(int i, char ch){
if (i < 0){
i=0;
}
else if (i > this.n){
i=this.n;
}
this.value[i]=ch;
}
public synchronized MyStringBuffer insert(int i, String s){
if (this.n==0 && i==0 || this.n>0 && i>=0 && i<=this.n){
if (s==null){
s="";
}
char[] temp=this.value;
if (this.value.length <this.n + s.length()){
this.value=new char[(this.value.length + s.length()) * 2];
for (int j=0; j<i; j++){
this.value[j]=temp[j];
}
}
for (int j=this.n-1; j>=i; j--){
this.value[j + s.length()]=temp[j];
}
for (int j=0; j<s.length(); j++){
this.value[i+j]=s.charAt(j);
}
this.n += s.length();
return this;
}
else {
throw new StringIndexOutOfBoundsException("i=" + i);
}
}
public synchronized MyStringBuffer append(String s){
return this.insert(this.n,s);
}
public synchronized MyStringBuffer delete(int begin, int end){
if (begin>=0 && begin<this.n && end>=0 && begin<=end){
if (end > this.n){
end=this.n;
}
for (int i=0; i<this.n-end; i++){
this.value[begin+i]=this.value[end+i];
}
this.n -= end-begin;
return this;
}
else {
throw new StringIndexOutOfBoundsException();
}
}
}