StringBuilder的使用与总结
StringBuilder 用于解决字符串频繁修改带来的内存消耗
所以将来有频繁修改字符串内容这样的操作时,首先使用StringBuiler
1 public class demo01 { 2 public static void main(String[] args) { 3 //内部默认为空字符串 4 StringBuilder builder = new StringBuilder(); 5 6 //内部默认为HelloWorld 7 StringBuilder builder1 = new StringBuilder("HelloWorld"); 8 9 //append用于在字符串末尾追加 10 builder.append("Try your best to learn Java"); 11 12 //replace用于替换 13 builder.replace(23,28,"js");//Try your best to learn js 14 String str = builder.toString(); 15 System.out.println(str); 16 17 builder.delete(0, 4);//your best to learn js 18 String str1 = builder.toString(); 19 System.out.println(str1); 20 //插入操作 21 builder.insert(0, "we ");//we your best to learn js 22 String str2 = builder.toString(); 23 System.out.println(str2); 24 } 25 }
builder.reverse()翻转字符串
1 /** 2 * builder.reverse()翻转字符串 3 * @author Administrator 4 *判断回文 5 */ 6 public class demo02 { 7 public static void main(String[] args) { 8 String str = "雾锁山头山锁雾"; 9 StringBuilder builder = new StringBuilder(str); 10 builder.reverse(); 11 String str1 = builder.toString(); 12 if(str.equals(str1)){ 13 System.out.println("yes"); 14 } 15 else{ 16 System.out.println("no"); 17 } 18 } 19 }
总结:
StringBuilder 是可变字符串,字符串的内容计算建议采用StringBuilder实现,这样性能会好一些;
java的字符串连接过程是利用StringBuilder实现的
String s ='ab'; String s1 = s+'de'+1; String s1 = new StringBuilder(s).append("de").append("1").toString();
StringBuffer是线程安全的,同步处理,性能稍慢;
StringBuilder是非线程安全的,并发处理,性能稍快;