Java StringBuffer

append

public static void main(String[] args) {
    // TODO Auto-generated method stub
    StringBuffer sb = new StringBuffer();
    sb.append("hello furong");
    System.out.println(sb.toString());
}
hello furong

insert

public static void main(String[] args) {
    // TODO Auto-generated method stub
    StringBuffer sb = new StringBuffer();
    sb.append("hello furong");
    sb.insert(1, "XXX");
    System.out.println(sb.toString());
}
hXXXello furong

replace

public static void main(String[] args) {
    // TODO Auto-generated method stub
    StringBuffer sb = new StringBuffer();
    sb.append("hello furong");
    sb.replace(1, 4, "XXX");
    System.out.println(sb.toString());
}
hXXXello furong

StringBuffer
对比String,可以实现字符串的修改

public class Str {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        StringBuffer sb = new StringBuffer();
        sb.append("hello furong");
        System.out.println(sb.toString());
        replace(sb);
        System.out.println(sb.toString());
    }

    public static void replace(StringBuffer sb) {
        sb.replace(0, 20, "hello quange");
    }
}
hello quange

String
对比StringBuffer,不能实现字符串的修改

public class Str {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s = "hello furong";
        replace(s);
        System.out.println(s);
    }

    public static void replace(String s) {
        s = "hello quange";
    }
}
hello furong

StringBuilder
对比StringBuffer,在字符串缓冲区被单个线程使用的时候,使用StringBuilder比StringBuffer速度快

原文地址:https://www.cnblogs.com/zhangxuechao/p/11709412.html