StringBuilder类
常用构造方法:(跟String类型用法上很像,但比String类型更加节约资源)
- public StringBuilder():空参构造
- public StringBuilder(String str):String型字符串作为参数进行构造
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder sb1 = new StringBuilder();
System.out.println(sb1);
StringBuilder sb2 = new StringBuilder("TIEI");
System.out.println(sb2);
}
}
输出结果:
TIEI
常用方法:
- public StringBuilder append(…):添加任意类型数据的字符串形式,并返回当前对象自身。//append:附加,增补。
- public String toString():将当前StringBuilder对象转换为String对象。
- public String reverse():将缓冲区内容转换为字符串。
apoend()、reverse()方法:
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder sb1 = new StringBuilder();
sb1.append(1);
sb1.append('中');
sb1.append("qwer");
System.out.println(sb1);
//由于apend()方法返回值仍是StrinBuilder类对象,所以就可以像这样链式调用
sb1.append(1).append('中').append("qwer");
System.out.println(sb1);
sb1.reverse();
System.out.println(sb1);
sb1.reverse();
System.out.println(sb1);
}
}
输出结果:
1中qwer
1中qwer1中qwer
rewq中1rewq中1
StringBuiler类与String类之间的转化:
//String->StringBuilder
StringBuilder sb = new StringBuilder(string);
//StringBuilder->String
String s=sb.toString();