天天看點

Java 字元串 之 字元串StringBuffer

http://www.verejava.com/?id=16993039377589
/**
    知識點: 可變字元串對象 StringBuffer
        1. 什麼是StringBuffer
        2. 為什麼用StringBuffer
            一般用在很多字元串相連接配接的情況
        3. StringBuffer的操作和應用
*/
public class TestStringBuffer {
    
    public static void main(String[] args) {
        String str = "";
        //執行個體化一個空的字元緩沖區
        StringBuffer strBuffer = new StringBuffer();
        for (int i = 0; i < 100; i++) {
            str += i + ",";
            strBuffer.append(i).append(",");
        }
        //輸出字元緩沖區的字元串
        System.out.println(strBuffer.toString());

        //1. 字元串追加
        StringBuffer buffer = new StringBuffer();
        buffer.append("How");
        buffer.append(" your");

        //2. 字元串的輸出
        System.out.println(buffer.toString());

        //3. 字元串的替換
        buffer.replace(4, 9, "you");
        System.out.println(buffer.toString());

        //4. 字元串插入索引為3的後面
        buffer.insert(3, " are");
        System.out.println(buffer.toString());

        //5. 字元串的截取
        System.out.println(buffer.substring(0, 4));

    }
}