public class Test
{
public static void main(String[] args)
{
StringBuffer a = new StringBuffer("One");
StringBuffer b = new StringBuffer("Two");
System.out.println ("begin a is :" + a);
System.out.println ("begin b is :" + b);
System.out.println ("swap start");
Test.swap(a,b);
System.out.println ("swap end\n");
System.out.println("now a is " + a +"\nnow b is " + b);
}
static void swap(StringBuffer a1, StringBuffer b1)
{
System.out.println ("a1 = " + a1);
System.out.println ("b1 = " + b1);
System.out.println ("append( \" more\")");
a1.append(" more");
System.out.println ("a1 = " + a1);
b1 = a1;
b1.append(" more");
System.out.println ("b1 = " + b1);
}
}
简单点的,最基本的各种数据类型的连接
public class StringBufferTest {
public static void main(String[] args) {
char[] charString={'A','B','C','D','E','F','G','H'};
String string="this is a test message!";
StringBuffer stringBuffer=new StringBuffer();
stringBuffer.append("----").append(charString).append(string);
stringBuffer.toString();
System.out.println(stringBuffer);
}
}
稍稍难一点的,可以利用StringBuffer打印一个字符组成的小矩形,例子如下
public class StringBufferDemo {
public static void main(String[] args) {
System.out.println(drawRectangle(6, 4));
}
public static String drawRectangle(int row,int coloum) {
StringBuffer stringBuffer=new StringBuffer();
for (int i = 0; i < row; i++) {
for (int j = 0; j < coloum; j++) {
stringBuffer.append("*");
}
stringBuffer.append("\n");
}
return stringBuffer.toString();
}
}
public class Test{
publci static void main(String []args){
StringBuffer sb = new StringBuffer();
sb.append("hello");
System.out.println(sb); //这里只会输出hello
sb.append(" world!");
System.out.println(sb); //这里就将会输出hello world!
}
}
StringBuffer 一般用到append追加的一个方法;
然后就是一个toString()