编写程序,对StringBuffer对象进行追加,插入和修改缓冲区长度等操作;
class StringDemo{public static void main(String[] args){boolean b=true;int i=321;long l=123456;String s1=new String("Hello,world!");StringBuffer s2=new StringBuffer(s1);System.out.println("s1的内容是:"+s1);System.out.println("s2的内容是:"+s2);System.out.println("s2的字符个数:"+s2.length());System.out.println("s2的缓冲区长度"+s2.capacity());//一般比字符个数要长System.out.println("s2插入数据后:"+ s2.append(b).insert(0,i).insert(3,l));//链式编程System.out.println("s2内的字符个数:"+s2.length());System.out.println("s2的缓冲区长度:"+s2.capacity());s2.setLength(10);//重设长度System.out.println("s2重设长度后:"+s2);}
}
s1的内容是:Hello,world!
s2的内容是:Hello,world!
s2的字符个数:12
s2的缓冲区长度28
s2插入数据后:321123456Hello,world!true
s2内的字符个数:25
s2的缓冲区长度:28
s2重设长度后:321123456H进程已结束,退出代码0
(1)使用默认构造方法进行赋值;
String s1=new String("Hello,world!");StringBuffer s2=new StringBuffer(s1);
(2)返回缓冲区长度,其一般会大于length()
System.out.println("s2的缓冲区长度"+s2.capacity());//一般比字符个数要长
s2的字符个数:12
s2的缓冲区长度28
(3)链式编程,在s2的后面添上b,0的位置插入i,3的位置插入l;
System.out.println("s2插入数据后:"+ s2.append(b).insert(0,i).insert(3,l));//链式编程
s2的内容是:Hello,world!
s2插入数据后:321123456Hello,world!true
(4) 重设长度
s2.setLength(10);//重设长度System.out.println("s2重设长度后:"+s2);
s2重设长度后:321123456H
String与StringBuffer的区别:
String类是常量类型,创建后不能进行改动,只能做查找,比较,连接等操作;
StringBuffer类不同,可以随意修改字符串的内容;
此外,由于String类是常量类型,在对其操作后,并没有改变它的内容;而StringBuffer则相反;
class StringDemo1{public static void main(String[] args) {String s=new String("Hello");System.out.println("s改动后的的内容:"+s.replace('e','E'));//替换操作System.out.println("s的内容:"+s);StringBuffer sb=new StringBuffer("I like the world!");System.out.println("sb改动后的内容:"+sb.append("Tt is true!!!"));//增添操作System.out.println("sb的内容:"+sb);}
}
s改动后的的内容:HEllo
s的内容:Hello
sb改动后的内容:I like the world!Tt is true!!!
sb的内容:I like the world!Tt is true!!!进程已结束,退出代码0