String1

String1
String1

//【例4.1】常量串的基本操作。

package dataStructure.linearList;

public final class String1

{

private final char[] value; //字符数组,私有最终变量,只能赋值一次

public String1() //构造一个空串

{

this.value = new char[0];

}

public String1(char[] value) //以字符数组构造串对象

{

this.value = new char[value.length]; //当value==null时,Java抛出空对象异常

for (int i=0; i

this.value[i] = value[i];

}

public String1(String1 str) //拷贝构造方法,复制对象

{

this(str.value);

}

public String1(https://www.360docs.net/doc/0616186957.html,ng.String Original)

{this.value=Original.toCharArray();

}

public int length() //返回字符串的长度

{

return this.value.length;

}

public char charAt(int index) //返回串中序号为index的字符

{

if (index<0 || index >= this.value.length)

throw new StringIndexOutOfBoundsException(index);//抛出字符串索引越界异常return this.value[index];

}

public String toString()

{

return new String(this.value); //https://www.360docs.net/doc/0616186957.html,ng.String实现为return this;

}

public String1 concat(String1 str) //返回当前串与指定串str连接生成的新串{ //不改变当前串

if (str==null || str.length()==0) //欲连接的串为空时,返回当前串return this;

char[] buffer = new char[this.value.length + str.length()];

int i;

for (i=0; i

buffer[i] = this.value[i];

for (int j=0; j

buffer[i+j] = str.value[j];

return new String1(buffer);

}

public String1 substring(int begin, int end) //返回串中序号从begin至end-1的子串{

if (begin < 0)

throw new StringIndexOutOfBoundsException(begin);

if (end > value.length)

throw new StringIndexOutOfBoundsException(end);

if (begin > end)

throw new StringIndexOutOfBoundsException(end - begin);

if (begin==0 && end == value.length)

return this;

else

{

char[] buffer = new char[end - begin];

for (int i=0; i< buffer.length; i++) //复制子串

buffer[i] = this.value[i+begin];

return new String1(buffer);

}

}

public String1 substring(int begin) //返回串中序号从begin至串尾的子串{

return substring(begin, value.length);

}

public String1 insert(int index, String1 str) //在source串的index处插入str

{ //返回插入后的串,source串不变char[] buffer = new char[this.value.length + str.length()];

for (int i=0; i< index; i++) //复制子串

buffer[i] = this.value[i];

for (int j=0; j< str.length(); j++) //复制子串

buffer[index+j] = str.charAt(j);

for (int k=index; k< this.value.length; k++) //复制子串

buffer[str.length()+k] = this.value[k];

return new String1(buffer);

}

public String1 delete(int begin, int end) //删除source串中从begin到end-1处的子串{ //返回删除后的串,source串不变char[] buffer = new char[this.value.length-end+begin];

for (int i=0; i< begin; i++) //复制子串

buffer[i] = this.value[i];

for (int k=end; k< this.value.length; k++) //复制子串

buffer[begin+k-end] = this.value[k];

return new String1(buffer);

}

public char[] getValue() {

return value;

}

}

相关主题
相关文档
最新文档