StringBuilder基本用法

//StringBuilder用法
public class StringBuilderTest {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        //追加字符串
        sb.append("Java");
        //sb = "Java";
        System.out.println(sb);
        //插入
        sb.insert(0, "Hello ");
        //sb = "Hello Java";
        System.out.println(sb);
        //替換
        sb.replace(5, 6, ",");
        //sb = "Hello,Java";
        System.out.println(sb);
        //刪除
        sb.delete(5, 6);
        //sb = "HelloJava";
        System.out.println(sb);
        //反轉
        sb.reverse();
        System.out.println(sb);
        //輸出9
        System.out.println(sb.length());
        //輸出16
        System.out.println(sb.capacity());
        //改變StringBuilder的長度,只保留前面部分
        sb.setLength(5);
        //sb = "avaJo";
        System.out.println(sb);
    }
}

 

相關文章
相關標籤/搜索