为什么要用StringBuilder
StringBuilder是一个可变的字符串类(StringBuilder对象中的内容可变)
为什么不用String拼接呢?
因为拼接字符串会造成前两个字符串的空间浪费
package dayhou40.day44; public class test { public static void main(String[] args) { String s="hello"; s+="world"; System.out.println(s); } }
StringBuilder的构造方法
public StringBuilder();不带任何参数的构造
package dayhou40.day44; public class StringBuildertest { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); System.out.println(sb); } }
StringBuilder sb = new StringBuilder(s1+s2);
package dayhou40.day44; public class StringBuildertest { public static void main(String[] args) { String s1="hello"; String s2="world"; StringBuilder sb = new StringBuilder(s1+s2); System.out.println(sb); } }
StringBuilder中的添加
package dayhou40.day44; public class StringBuilderApplication { public static void main(String[] args) { StringBuilder sb1 = new StringBuilder(); StringBuilder sb2=sb1.append("hello"); System.out.println(sb1); System.out.println(sb2); System.out.println(sb1==sb2); } }
StringBuilder()中的append方法可以添加任意数据类型 并且将添加的数据返回到数据本身
StringBuilder中的反转
采用reverse();方法反转字符串序列
package dayhou40.day44; public class StringBuilderApplication { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); sb.append("hello"); sb.append("world"); sb.append(100).append('c'); System.out.println("反转之前的:"+sb); sb.reverse(); System.out.println("反转之后的:"+sb); } }
StringBuilder和String的相互转换
将StringBuilder转为String类型
package dayhou40.day44; public class StringBuilderApplication { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); sb.append("hello"); String s=sb.toString(); System.out.println(s); } }
注意 不能直接用String s=sb;(因为类型不一样会报错)
将String转为StringBuilder
package dayhou40.day44; public class StringBuilderApplication { public static void main(String[] args) { String s="hello"; StringBuilder sb = new StringBuilder(s); System.out.println(sb); } }