9.2 StringBuffer和StringBuilder
字符串有一个操作是多个字符串前后相连。例如:
public static void main(String[]args){
String s1="good";
String s2=s1+" bye";
}
这样的操作其实是不怎么提倡的,因为String对象一旦创建了,是不能再改变它的值了,于是每一次+的操作,实际上都需要新创建一个StringBuffer对象。编译器会把上面的代码变成这样:
public static void main(String[]args){ StringBuffer buffer=new StringBuffer("good"); buffer.append(" bye!"); buffer.append(" We are good."); String s2=buffer.toString(); System.out.println(s2);}
1.append
每使用一次+,就创建一个新的String对象,实际上当反复出现+操作的时候,是很耗费资源的。所以多段拼接,都提倡使用StringBuffer或者StringBuilder。它们都有一个方法,append,这个方法又返回拼接后的StringBuffer对象,所以可以连着用,那么拼接操作就变成了这样:
public static void main(String[]args){ //这是一个sql语句; String code="020100"; String courseId="1"; StringBuffer sql=new StringBuffer("select * from chapter_quiz where code='").append(code).append("' and id=").append(courseId).append(" order by queue"); System.out.println(sql);}
StringBuffer还可以直接转换成String,调用toString方法就可以了。
public static void main(String[]args){ StringBuffer s1=new StringBuffer("good"); s1.append(" bye"); String s=s1.toString(); System.out.println(s);}
2.insert
如果不是在末尾拼接,而是中间,那么就要用insert操作了
public static void main(String[]args){ StringBuffer s1=new StringBuffer("bye"); s1.insert(0, "good "); String s=s1.toString(); System.out.println(s);}
insert第一个参数是指从何处插入,第二个参数是要插入的内容,如果第一个参数是0,如上所示,那表示在最开头拼接。