Java 字符串之---------StringBuilder与StringBuffer的使用

StringBuilder与StringBuffer类;

所属的包:java.lang包,不需要导入包;
   StringBuffer 1.0 版本 ,StringBuilder 1.5 版本;
   继承关系:没有自己继承的父类,默认继承Object类,实现Serializable,CharSequence,Appendable;
   StringBuffer和StringBuiler没有compareTo()方法;
     StringBuffer和StringBuilder有一个String没有的方法append();拼接;
   特性:可以扩容,内容和长度都可以改变,可变字符串,char[] value;动态扩容;
   对象的构建:
    无参数构建方法:构建一个默认长度是16个看见的对象 char []
    StringBuilder s = new StringBuilder();

public StringBuilder() {
        super(16);
    }

利用给定的空间长度创建对象 char[]
    StringBuilder s = new StringBuilder(20);//字符串容量是20,我们给定的

public StringBuilder(int capacity) {
        super(capacity);
    }

利用带String参数的构造方法,创建一个长度为 参数长度+16个的对象;
    StringBuilder s = new StringBuilder(“abc”);下面代码是源码

public StringBuilder(String str) {
        super(str.length() + 16);//可以看出StringBuilder对象的容量是字符串长度+16
        append(str);
    }

(3)常用的方法:
   append()
     在拼接字符串的时候可以频繁的使用此方法,提高性能;
     不需要返回值,但是需要传参(int / String / char / boolean / char [] / float / long / Object / StringBuffer );
     append(char[],int offset,int length);//举个例子;
      StringBuilder s = “abc”;
      char[] c = {‘a’,‘b’,‘c’};
      s.append(c,0,1);//将字符串c从0号索引开始添加1个字符拼接到s的后面;

public StringBuilder append(StringBuffer sb) {
        super.append(sb);//调用父类AbstractStringBuilder的append方法
        return this;
    }
public AbstractStringBuilder append(String str) {
        if (str == null)//如果要添加的str==null,那么返回this
            return appendNull();
        int len = str.length();
        ensureCapacityInternal(count + len);//确定数组容量是否够用
        str.getChars(0, len, value, count);//将str的0-len长度的字符 ,依次拷贝到value数组的count位置
        count += len;//count是value数组真实存储的字符数量 
        return this;
    }

ensureCapacity(int minimumCapacity)
     确保字符型底层char[]的容量够用;

private void ensureCapacityInternal(int minimumCapacity) {
       
        if (minimumCapacity - value.length > 0) {
        //如果最小的数组长度不够用,那么就创建一个新的数组,最后将这个新的数组的值赋值给value数组
            value = Arrays.copyOf(value,
                    newCapacity(minimumCapacity));
        }
    }

length()
     字符串的有效元素个数(长度);
     返回值类型是int型;

	public int length() {
        return count;//count就是我们上文提到的有效元素个数
    }

capacity ();
     字符串底层的容量;创建对象的时候的字符个数+16;
   charAt(int index)
     找到给定的索引对应的char值并且返回;
     返回值类型是char型;

public char charAt(int index) {
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        return value[index];
    }

codePointAt(int index)
     找到给定索引对应的Unicode值,并且返回;
     返回值类型是int型;

public int codePointAt(int index) {
        if ((index < 0) || (index >= count)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return Character.codePointAtImpl(value, index, count);
    }

subString(int start[,int end])
     截取给定位置的字符串;
     返回值类型是String型;

	public String substring(int start) {
        return substring(start, count);//从给定位置start开始截取到结束
    }


    public String substring(int start, int end) {
    //从给定位置start开始截取到end位置,end位置取不到
        if (start < 0)
            throw new StringIndexOutOfBoundsException(start);
        if (end > count)
            throw new StringIndexOutOfBoundsException(end);
        if (start > end)
            throw new StringIndexOutOfBoundsException(end - start);
        return new String(value, start, end - start);
    }

delete(int start,int end)
     StringBuilder类中的独有方法,String类里面没有;
     删除给定位置的字符串,不需要返回值;

	public AbstractStringBuilder delete(int start, int end) {
        if (start < 0)
            throw new StringIndexOutOfBoundsException(start);
        if (end > count)
            end = count;
        if (start > end)
            throw new StringIndexOutOfBoundsException();
        //上面这些代码都是为了抛出异常
        int len = end - start;
        if (len > 0) {
        //将value数组从start+len开始复制count-end个,到value数组从start开始
       //简单一点就是保留start之前的元素,copy了end之后的元素
            System.arraycopy(value, start+len, value, start, count-end);
            count -= len;
        }
        return this;
    }

deleteCharAt(int index)
     String类里面没有的方法;
     删除给定index位置的字符;不需要返回值;

	public AbstractStringBuilder deleteCharAt(int index) {
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
            //将value数组在index之前的元素保留,然后复制从index+1开始的元素,复制count-index-1个
        System.arraycopy(value, index+1, value, index, count-index-1);
        count--;
        return this;
    }

intdexOf(String str[,int fromIndex])
     从给定索引位置开始找给定的字符串第一次出现的位置,并且返回索引;
     返回值类型是int型; 
       
   lastIndexOf(String str[,int fromIndex]);
     从给定位置开始找寻给定字符串最后一次出现的位置,并且返回索引;
     返回值类型是int型;
   setLength(int newlength);
     设置字符串的有效个数(newLength);但是不改变字符串的容量;
     没有返回值;

	public void setLength(int newLength) {
        if (newLength < 0)
            throw new StringIndexOutOfBoundsException(newLength);
        ensureCapacityInternal(newLength);

        if (count < newLength) {
            Arrays.fill(value, count, newLength, '\0');
        }

        count = newLength;
    }

insert(int index,value);
     将给定的字符添加到index位置;
     没有返回值;

public StringBuilder insert(int offset, Object obj) {
            super.insert(offset, obj);
            return this;
    }

public AbstractStringBuilder insert(int offset, String str) {
        if ((offset < 0) || (offset > length()))
            throw new StringIndexOutOfBoundsException(offset);
        if (str == null)
            str = "null";
        int len = str.length();
        ensureCapacityInternal(count + len);
        //从index+len开始,复制从offset开始,复制总的数量减去索引
        //此时的value从offset开始,里面有多余的元素len个,等会来替换掉
        System.arraycopy(value, offset, value, offset + len, count - offset);     
        str.getChars(value, offset);
        count += len;
        return this;
    }
void getChars(char dst[], int dstBegin) {
//将str 从0开始复制str的长度到dst[]
        System.arraycopy(value, 0, dst, dstBegin, value.length);
    }

replace(int start,int end,String str);
     从start开始到end的字符替换成str;
     没有返回值;

//这个和上一个极为相似
 public AbstractStringBuilder replace(int start, int end, String str) {
        if (start < 0)
            throw new StringIndexOutOfBoundsException(start);
        if (start > count)
            throw new StringIndexOutOfBoundsException("start > length()");
        if (start > end)
            throw new StringIndexOutOfBoundsException("start > end");

        if (end > count)
            end = count;
        int len = str.length();
        int newCount = count + len - (end - start);
        ensureCapacityInternal(newCount);

        System.arraycopy(value, end, value, start + len, count - end);
        str.getChars(value, start);
        count = newCount;
        return this;
    }

setCharAt(int index,char vlaue);
     将index位置的字符换成value;
     没有返回值;

public void setCharAt(int index, char ch) {
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        value[index] = ch;
    }

toString();
     将StringBuilder对象转换成String对象,并且返回;
     返回值类型是String型;

@Override
    public String toString() {
        // Create a copy, don't share the array
        return new String(value, 0, count);
    }

TrimToSize()
     将数组中无用的容量去掉;此时数组里面的长度和容量都是有效元素的个数;
     没有返回值;

public void trimToSize() {
        if (count < value.length) {
            value = Arrays.copyOf(value, count);
        }
    }
public static char[] copyOf(char[] original, int newLength) {
        char[] copy = new char[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

reverse()
     将字符串逆置,没有返回值;

@Override
    public StringBuilder reverse() {
        super.reverse();
        return this;
    }
 public AbstractStringBuilder reverse() {
        boolean hasSurrogates = false;
        int n = count - 1;
        for (int j = (n-1) >> 1; j >= 0; j--) {
            int k = n - j;
            char cj = value[j];
            char ck = value[k];
            value[j] = ck;
            value[k] = cj;
            if (Character.isSurrogate(cj) ||
                Character.isSurrogate(ck)) {
                hasSurrogates = true;
            }
        }
        if (hasSurrogates) {
            reverseAllValidSurrogatePairs();
        }
        return this;
    }

猜你喜欢

转载自blog.csdn.net/qq_40791843/article/details/91885243