java StringBuilder案例

biubiubiuo發表於2018-02-28

實現輸出字串的長度,容量(容量不夠則擴容),及內容

import java.util.Arrays;

public class MyStringBuilderDemo {
//任務:儲存字串並輸出長度及容量
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MyStringBuilder msb = new MyStringBuilder();
        msb.append("hello").append(",java").append("1234567");
        System.out.println("字串長度:"+msb.length());
        System.out.println("字串容量:"+msb.capacity());
        System.out.println("輸出字串:"+msb.toString());
    }

}

class MyStringBuilder{
    private char[] value;//字串的值
    private int count;//字串的長度
    public int length() {
        return count;
    }
    public int capacity() {
        return value.length;
    }
    
    public MyStringBuilder(){//預設給定陣列容量為16
        value = new char[16];
    }
    public MyStringBuilder(int capacity){//預設給定陣列容量為16
        value = new char[capacity];
    }
    
    //追加字串
    public MyStringBuilder append(String str) {
        int len = str.length();
        addength(count+len);
        //追加字串        追加的字串.getChars(追加字串的起始位置,結束為止,目標字串,開始寫入的位置)
        str.getChars(0, str.length(), value, count);
        count+=len;
        return this;
    }
    private void addength(int capacity) {//防止字串長度不夠,擴容陣列
        if(capacity -value.length>0) {
            int newlength;
            newlength = value.length*2+2;
            value = Arrays.copyOf(value, newlength);
        }
    }
    //輸出字串
    public String toString() {
        return new String(value,0,count);
    }
}

 

相關文章