手写StringBuilder

模仿Java中StringBuilder类底层实现,最近修改了一些复制数组的方法。

package mylang;

public final class MyStringBuilder {
    private char[] chars = new char[16];//数组初始长度设为16
    private int capacity = 0;//初始容量为0

    public MyStringBuilder(){}//默认无参构造方法

    public MyStringBuilder(String str){
        append(str);
    }

    //=============================私有的方法=======================================
    private char[] growCapacity(int newCapacity){//扩容方法
        if(newCapacity > chars.length){//判断是否需要扩容
            char[] charsNew;
            if(newCapacity > chars.length*2){//如果扩容2倍容量还是不足
                charsNew = new char[newCapacity];//定义新数组长度为需要的长度
            }else{
                charsNew = new char[chars.length*2];//容量充足则扩容为2倍长度
            }
            return charsNew;
        }else{
            return null;
        }
    }

    private void rangeCheck(int fromIndex){
        if(fromIndex < 0 || fromIndex > capacity-1){
            throw new StringIndexOutOfBoundsException("offset "+fromIndex+",length "+capacity);
        }
    }

    private void rangeCheck(int fromIndex,int toIndex){
        if(toIndex < fromIndex ||fromIndex < 0 || fromIndex > capacity-1 ||  toIndex > capacity-1){
            throw new StringIndexOutOfBoundsException("start "+fromIndex+",end "+toIndex+",length "+capacity);
        }
    }

    //==============================提供给外部的方法==================================
    public int capacity(){
        return capacity;//返回容量值
    }

    public int length(){
        return chars.length;//返回实体大小
    }

    public void append(char c){//追加字符
        char[] charsNew = growCapacity(capacity+1);
        if(charsNew == null){
            chars[capacity] = c;//保存新元素
        }else{
            System.arraycopy(chars,0,charsNew,0,chars.length);//原数组中的数据复制到新数组中
            charsNew[capacity] = c;//保存新元素
            chars = charsNew;//实体数组指针指向新数组
        }
        capacity++;//容量+1
    }

    public void append(char[] str){//追加字符数组
        append(str, 0, str.length);
    }

    public void append(char[] str,int offset,int len){//部分追加字符数组
        if(offset < 0 || offset > str.length -1|| len <0 || offset+len > str.length){
            throw new ArrayIndexOutOfBoundsException();//数组下标越界抛出异常
        }
        char[] charsNew = growCapacity(capacity+len);
        if (charsNew==null){
            System.arraycopy(str,offset,chars,capacity,len);//写入每个字符
        }else{
            System.arraycopy(chars,0,charsNew,0,chars.length);//原数组中的数据复制到新数组中
            System.arraycopy(str,offset,charsNew,capacity,len);//写入每个字符
            chars = charsNew;
        }
        capacity += len;//更新容量
    }

    public void append(String str){//追加字符串
        char[] tempChars = str.toCharArray();//字符串转化为字符数组
        append(tempChars);
    }

    public void append(int i){
        char[] tempChars = String.valueOf(i).toCharArray();
        append(tempChars);
    }

    public void append(long lng){
        char[] tempChars = String.valueOf(lng).toCharArray();
        append(tempChars);
    }

    public void append(float f){
        char[] tempChars = String.valueOf(f).toCharArray();
        append(tempChars);
    }

    public void append(double d){
        char[] tempChars = String.valueOf(d).toCharArray();
        append(tempChars);
    }

    public void append(boolean b){
        char[] tempChars = String.valueOf(b).toCharArray();
        append(tempChars);
    }

    public void append(MyStringBuilder sb){
        char[] str = sb.toString().toCharArray();
        append(str);
    }

    public void insert(int offset,char c){
        if(offset < 0 || offset > capacity){
            throw new StringIndexOutOfBoundsException("offset "+offset+",capacity "+capacity);
        }
        char[] charsNew = growCapacity(capacity+1);
        if(charsNew == null){
            System.arraycopy(chars,offset,chars,offset+1,capacity-offset+1);
            chars[offset] = c;
        }else{
            System.arraycopy(chars,0,charsNew,0,offset);//offset之前的元素复制
            charsNew[offset] = c;//offset位置添加新元素
            System.arraycopy(chars,offset,charsNew,offset+1,chars.length-offset-1);//原数组offset之后的复制到新数组
            chars = charsNew;//修改指针
        }
        capacity ++;//容量+1
    }

    public void insert(int index,char[] str,int offset,int len){
        if(index < 0 ||index > capacity ){
            throw new StringIndexOutOfBoundsException("offset "+index+",length "+capacity);
        }
        if(offset < 0 || offset > str.length -1|| len < 0 ||offset+len > str.length){
            throw new ArrayIndexOutOfBoundsException("start "+offset+",end "+len+",length "+str.length);//数组下标越界抛出异常
        }
        char[] charsNew = growCapacity(capacity+len);
        if(charsNew == null){
            System.arraycopy(chars,index,chars,index+len,capacity-index+1);//确定位置,后移
            System.arraycopy(str,offset,chars,index,len);//依次添加新元素
        }else{
            System.arraycopy(chars,0,charsNew,0,index);//index之前的元素复制
            System.arraycopy(str,offset,charsNew,index,len);//offset位置依次添加新元素
            System.arraycopy(chars,index,charsNew,index+len,capacity-index);//原数组offset之后的复制到新数组
            chars = charsNew;
        }
        capacity += len;//更新容量
    }

    public void insert(int offset,char[] str){
        insert(offset,str,0,str.length);
    }

    public void insert(int offset,String str){
        char[] tempChars = str.toCharArray();
        insert(offset, tempChars);
    }

    public void insert(int offset,int i){
        char[] tempChars = String.valueOf(i).toCharArray();
        insert(offset, tempChars);
    }

    public void insert(int offset,long lng){
        char[] tempChars = String.valueOf(lng).toCharArray();
        insert(offset, tempChars);
    }

    public void insert(int offset,float f){
        char[] tempChars = String.valueOf(f).toCharArray();
        insert(offset, tempChars);
    }

    public void insert(int offset,double d){
        char[] tempChars = String.valueOf(d).toCharArray();
        insert(offset, tempChars);
    }

    public void insert(int offset,boolean b){
        char[] tempChars = String.valueOf(b).toCharArray();
        insert(offset, tempChars);
    }

    public void insert(int offset, MyStringBuilder sb){
        char[] tempChars = String.valueOf(sb).toCharArray();
        insert(offset, tempChars);
    }

    public int indexOf(String str,int fromIndex){
        rangeCheck(fromIndex);
        if(str.length() > capacity-fromIndex-1) {//字符串的长度大于要比较的字符串长度
            return -1;
        }
        char[] tempChars = str.toCharArray();//转化为字符数组
        for (int i = fromIndex; i < capacity; i++) {
            if(tempChars[0] == chars[i]){
                boolean isExist = true;
                for (int j = 1; j < tempChars.length; j++) {
                    if(tempChars[j] != chars[i+j]){
                        isExist = false;
                        break;
                    }
                }
                if(isExist){
                    return i;
                }
            }
        }
        return -1;
    }

    public int indexOf(String str){
        return indexOf(str, 0);
    }

    public int lastIndexOf(String str,int fromIndex){
        rangeCheck(fromIndex);
        if(str.length() > capacity-fromIndex-1) {//字符串的长度大于要比较的字符串长度
            return -1;
        }
        char[] tempChars = str.toCharArray();
        for(int i = capacity-1 ; i >= fromIndex ; i -- ){
            if(tempChars[tempChars.length-1] == chars[i]){
                boolean isExist = true;
                for (int j = tempChars.length-2; j >= 0 ; j--) {
                    if(tempChars[j] != chars[i-tempChars.length+j+1]){
                        isExist = false;
                        break;
                    }
                }
                if(isExist){
                    return i-tempChars.length+1;
                }
            }
        }
        return -1;
    }

    public int lastIndexOf(String str){
        return lastIndexOf(str, 0);
    }

    public String substring(int start,int end){
        rangeCheck(start,end);
        return String.valueOf(chars, start,end);
    }

    public String subString(int start){
        return substring(start, capacity-1);
    }

    public char charAt(int index){
        rangeCheck(index);
        return chars[index];
    }

    public void setCharAt(int index,char ch){
        rangeCheck(index);
        chars[index] = ch;
    }

    public void replace(int start,int end,String str){
        rangeCheck(start,end);
        char[] tempChars = str.toCharArray();
        char[] charsNew = growCapacity(capacity+tempChars.length+start-end);
        if(charsNew == null){
            for (int i = capacity - 1; i >= end; i--) {
                chars[i + tempChars.length + start - end] = chars[i];
            }
            System.arraycopy(tempChars,0,chars,start,tempChars.length);
        }else{
            for(int i = capacity-1;i >= end;i--){
                charsNew[i+tempChars.length+start-end] = chars[i];
            }
            System.arraycopy(tempChars,0,charsNew,start,tempChars.length);
            chars = charsNew;
        }
        capacity += tempChars.length+start-end;
    }

    public void deleteCharAt(int index){
        rangeCheck(index);
        System.arraycopy(chars,index+1,chars,index,capacity-index-1);
        capacity --;
    }

    public void delete(int start,int end){
        rangeCheck(start,end);
        System.arraycopy(chars,end+1,chars,start,capacity-end-1);//元素依次前移
        capacity -= end-start+1;//更新容量值
    }

    @Override
    public String toString(){//重写父类toString(方法)
        return new String(chars,0,capacity);//返回一个String对象,利用String的构造方法
    }

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值