String的部分源碼分析(substring、startsWith、endsWith)(一)

1.String的substring方法源碼:

       public String substring(int beginIndex) {

//判斷開始位置是否小於0
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }


        int subLen = value.length - beginIndex;

//判斷開始位置是否超出該字符串長度
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }

//如果開始位置爲0,則截取的字符串和原字符串爲同一字符串;否則將通過String構造方法,傳遞字符串,開始位置和截取長度獲取字符串
        return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
    }

  public String(char value[], int offset, int count) {

//判斷開始位置是否小於0
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }

//判斷開始位置是否小於0
        if (count < 0) {
            throw new StringIndexOutOfBoundsException(count);
        }
        // Note: offset or count might be near -1>>>1.

//判斷是否滿足條件
        if (offset > value.length - count) {
            throw new StringIndexOutOfBoundsException(offset + count);
        }

//通過copyOfRange方法,傳遞字符串數組,開始位置和結束位置獲取字符串
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }

  public static char[] copyOfRange(char[] original, int from, int to) {
        int newLength = to - from;
        if (newLength < 0)
            throw new IllegalArgumentException(from + " > " + to);
        char[] copy = new char[newLength];
        System.arraycopy(original, from, copy, 0,
                         Math.min(original.length - from, newLength));
        return copy;
    }

2.String的startsWith方法源碼:

public boolean startsWith(String prefix, int toffset) {

//被比較的字符串,轉換爲字符數組

        char ta[] = value;

//比較開始的起始位置 

        int to = toffset;

//比較的字符串轉換爲字符數組

        char pa[] = prefix.value;

        int po = 0;

//比較的字符串長度

        int pc = prefix.value.length;
        //判斷比較的起始點是否小於0或者起始點的開始位置無法將比較字符串比較完
        if ((toffset < 0) || (toffset > value.length - pc)) {
            return false;

        }

//循環比進行對比較字符串數組的字符一個一個比較是否相等

        while (--pc >= 0) {

//被比較字符串的從起始點開始與比較字符串數組一一比較

            if (ta[to++] != pa[po++]) {
                return false;
            }
        }
        return true;

    }


3.String的endsWith方法源碼:

public boolean endsWith(String suffix) {

//巧妙的使用了startsWith方法,計算出比較的開始位置(被比較串長度-去比較的串長度)
        return startsWith(suffix, value.length - suffix.value.length);
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章