范例1:StringBuffer基本使用
public class Demo {
public static void main(String[] args) {
// StringBuffer不能直接复制实例化
StringBuffer buf = new StringBuffer();
buf.append("Hello").append("World").append("!!");
change(buf);//引用传递
System.out.println(buf);
}
public static void change(StringBuffer temp) {
temp.append("\n").append("Java");
}
}
=============分割线=============
范例2:StringBuffer类的构造方法:public StringBuffer(String str)
public class Demo {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer("Hello World!");
System.out.println(buf);
}
}
=============分割线=============
范例3:append()方法:public StringBuffer append(String str)
public class Demo {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer("Hello");
buf.append("\tJava");
System.out.println(buf);
}
}
=============分割线=============
范例4:将StringBuffer转为String
·利用toString()将StringBuffer转为String
public class Demo {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer("Hello");
String str = buf.toString();
System.out.println(str);
}
}
=============分割线=============
范例5:String类里面有提供和StringBuffer比较的方法:public boolean contentEquals(StringBuffer sb)
public class Demo {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer("Hello");
System.out.println("Hello".contentEquals(buf));
}
}
=============分割线=============
范例6:字符串反转:public StringBuffer reverse();
public class Demo {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer("霸王别姬");
System.out.println(buf.reverse());
}
}
=============分割线=============
范例7:指定位置添加数据:public StringBuffer insert(int offset,数据类型 变量);
public class Demo {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer("Hello");
buf.insert(5, " Java!").insert(0, "欢迎!");
System.out.println(buf);
}
}
=============分割线=============
范例8:删除部分数据:public StringBuffer delete(int start ,int end)
public class Demo {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer("Hello World");
System.out.println(buf.delete(0, 5));
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/98e035728692d846f758f255e131c5cd.png)