1、(实现StringBuilder类)在Java库中提供了String Builder类,给出你自己定义的String Builder类:MyStringBuilder类,并实现下面方法并设计主类测试她:
Public MyStringBuilder(String s);
Public MyStringBuilder append(MyStringBuilder s);
Public MyStringBuilder append(int i);
Public int length();
Public char charAt(int index);
Public MyStringBuilder toLowerCase();
Public MyStringBuilder subString(int begin,int end);
Public String toString();
package assignment;
public class MyStringBuilder {
private char[] value;
private int count;
public MyStringBuilder(String s){
value = s.toCharArray();
count = value.length;
}
public MyStringBuilder append(MyStringBuilder s){
if(s == null){
throw new NullPointerException("Null MyStringBuilder");
}else {
char[] midValue = s.toString().toCharArray();
char[] newValue = new char[midValue.length + count];
System.arraycopy(midValue,0,newValue,midValue.length,midValue.length);
System.arraycopy(value,0,newValue,0,value.length);
value = newValue;
count += s.length();
return this;
}
}
public MyStringBuilder append(int i){
char[] newValue = new char[count + 1];
System.arraycopy(value,0,newValue,0,count);
newValue[count++] = (char) (48 + i);
value = newValue;
return this;
}
public int length(){
return count;
}
public char charAt(int index){
if (index >= value.length){
throw new IndexOutOfBoundsException("Index out of Bounds");
}else {
return value[index];
}
}
public MyStringBuilder toLowerCase(){
for (int i = 0;i < count;i++ ){
value[i] = Character.toLowerCase(value[i]);
}
return this;
}
public MyStringBuilder subString(int begin,int end){
if (begin < 0 || end >= count || begin > end){
throw new RuntimeException("index error");
}
return new MyStringBuilder(String.copyValueOf(value,begin,end - begin));
}
public String toString(){
return String.valueOf(value);
}
}
package assignment;
public class testMyStringBuilder {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyStringBuilder s1=new MyStringBuilder("Hello");
System.out.println(s1.length());
s1.append(new MyStringBuilder("World"));
System.out.println(s1.toString());
s1.append(1);
System.out.println(s1.toString());
System.out.println(s1.charAt(1));
s1.toLowerCase();
System.out.println(s1.toString());
System.out.println(s1.subString(0, 5).toString());
}
}