public class OperationString { public static void main(String[] args) { String str[]=new String [4];//定义长度为4的字符串数组 str[0]="first"; str[1]="second"; StringBuffer sb1= new StringBuffer(str[0]);//利用字符串str[0]来构造一个StringBuffer,sb1内容为"first"; sb1.insert(0,str[1]);//在该StringBuffer对象位置0处之前,插入字符串str[1],StringBuffer,sb1内容为"secondfirst"; str[2]=new String (sb1);//由StringBuffer对象sb1来构造生成字符串str[2],即将sb1的值赋值给str[2],此时str[2]内容为"secondfirst" StringBuffer sb2=new StringBuffer();//缺省构造一个StringBuffer对象sb2,初始内容为空,sb2内容为:"" sb2.append('D');//在StringBuffer对象sb2的末尾追加字符'D',sb2内容为:"D" sb2.append(" admin");//在StringBuffer对象sb2的末尾追加字符串" admin",sb2内容为"D admin" sb2.insert(1, "ear");//在该StringBuffer对象sb2的位置1处即字符'D'后插入字符串"ear",sb2内容为"Dear admin" str[3]=new String(sb2);//由StringBuffer对象sb2来构造生成字符串str[3],即将sb2的值赋值给str[3],str[3]="Dear admin" for(int i=0;i<4;i++) { System.out.println("str["+i+"]="+str[i]); } } }
运行结果: