java8 string 源码

 比较常用的一些方法

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** final的char数组存储string的值 */
    private final char value[];
    /** 省略号 **/
    public boolean equals(Object anObject) {
        if (this == anObject) {//先判断地址值,相等就返回true
            return true;
        }
        if (anObject instanceof String) {//判断参数是否为String类型,不是就返回false
            String anotherString = (String)anObject;
            int n = value.length;
            /** 判断调用方法的String和形参长度是否相等,不等就返回false **/
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {//遍历比较相对应的位置的字符地址值,不等就返回false
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

    public boolean startsWith(String prefix) {
        return startsWith(prefix, 0);//调用下面的方法
    }
    public boolean startsWith(String prefix, int toffset) {
        char ta[] = value;//原对象char数组
        /** 需要比较字符的开始位置 **/
        int to = toffset;
        char pa[] = prefix.value;//形参char数组
        int po = 0;
        int pc = prefix.value.length;//形参长度 也是需要比较字符的次数
        if ((toffset < 0) || (toffset > value.length - pc)) {
            return false;
        }
        while (--pc >= 0) {
            if (ta[to++] != pa[po++]) {//地址值不等就返回false
                return false;
            }
        }
        return true;
    }
    public boolean endsWith(String suffix) {//调用上面的方法
        return startsWith(suffix, value.length - suffix.value.length);
    }

    public boolean contains(CharSequence s) {
        return indexOf(s.toString()) > -1;//调用的indexOf方法
    }
    public int indexOf(String str) {
        return indexOf(str, 0);//调用下个方法
    }
    public int indexOf(String str, int fromIndex) {//调用下个方法
        return indexOf(value, 0, value.length,str.value, 0, str.value.length, fromIndex);
    }
    static int indexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex) {
        /**fromIndex是传递参数值为0,sourceCount值为this.value.length**/
        if (fromIndex >= sourceCount) {// 调用indexOf方法的对象长度小于等于0就返回
            return (targetCount == 0 ? sourceCount : -1);
        }
        if (fromIndex < 0) {//保证fromIndex最小为0 
            fromIndex = 0;
        }
        /**targetCount -> indexOf(String str) str的长度 **/
        if (targetCount == 0) {//形参长度为0返回fromIndex的值
            return fromIndex;
        }
        /**first -> indexOf(String str) str的value,targetOffset = 0**/
        char first = target[targetOffset];//形参第一个字符
        /**sourceOffset =0,sourceCount->this.value.length,targetCount形参长度**/
        int max = sourceOffset + (sourceCount - targetCount);
        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }
            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j]
                        == target[k]; j++, k++);

                if (j == end) {
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }

    public int lastIndexOf(String str) {
        return lastIndexOf(str, value.length);
    }
    public int lastIndexOf(String str, int fromIndex) {
        return lastIndexOf(value, 0, value.length,
                str.value, 0, str.value.length, fromIndex);
    }
    static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
            String target, int fromIndex) {
        return lastIndexOf(source, sourceOffset, sourceCount,
                       target.value, 0, target.value.length,
                       fromIndex);
    }
    static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex) {
        int rightIndex = sourceCount - targetCount;
        if (fromIndex < 0) {
            return -1;
        }
        if (fromIndex > rightIndex) {
            fromIndex = rightIndex;
        }
        if (targetCount == 0) {
            return fromIndex;
        }

        int strLastIndex = targetOffset + targetCount - 1;
        char strLastChar = target[strLastIndex];
        int min = sourceOffset + targetCount - 1;
        int i = min + fromIndex;

    startSearchForLastChar:
        while (true) {
            while (i >= min && source[i] != strLastChar) {
                i--;
            }
            if (i < min) {
                return -1;
            }
            int j = i - 1;
            int start = j - (targetCount - 1);
            int k = strLastIndex - 1;

            while (j > start) {
                if (source[j--] != target[k--]) {
                    i--;
                    continue startSearchForLastChar;
                }
            }
            return start - sourceOffset + 1;
        }
    }

    public String substring(int beginIndex/**截取开始index**/) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        int subLen = value.length - beginIndex;
        if (subLen < 0) {//截取开始index超出自身长度
            throw new StringIndexOutOfBoundsException(subLen);
        }
        //调用下个方法
        return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);                  
    }
    public String(char value[], int offset, int count) {
        if (offset < 0) {//开始index
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count <= 0) {//需要字符的个数   小于等于0
            if (count < 0) {//小于0 抛异常
                throw new StringIndexOutOfBoundsException(count);
            }
            if (offset <= value.length) {//开始index小于形参长度 & 需要0个字符 直接返回空串
                this.value = "".value;
                return;
            }
        }
        if (offset > value.length - count) {//开始index大于 形参长度减去所需字符个数
            /**虽然开始index小于形参长度,但是剩下的字符数量不够所需要的字符数量**/
            throw new StringIndexOutOfBoundsException(offset + count);
        }
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }
    public String substring(int beginIndex, int endIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        if (endIndex > value.length) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        int subLen = endIndex - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return ((beginIndex == 0) && (endIndex == value.length)) ? this
                : new String(value, beginIndex, subLen);//调用上个方法
    }

    public CharSequence subSequence(int beginIndex, int endIndex) {
        return this.substring(beginIndex, endIndex);
    }

    public String replace(char oldChar, char newChar) {
        if (oldChar != newChar) {
            int len = value.length;//原本字符串的长度
            int i = -1;
            char[] val = value; //原本字符串的新引用
            while (++i < len) {//找到oldChar在原字符串的index值
                if (val[i] == oldChar) {
                    break;
                }
            }
            if (i < len) {//oldChar在原字符串的index值小于原字符串长度
                char buf[] = new char[len];//新建char[]
                for (int j = 0; j < i; j++) {//oldChar之前的字符赋值到新数组
                    buf[j] = val[j];
                }
                while (i < len) {//oldChar开始以后元素赋值到新数组,并且oldChar替换为newChar 
                    char c = val[i];
                    buf[i] = (c == oldChar) ? newChar : c;
                    i++;
                }
                return new String(buf, true);
            }
        }
        return this;
    }

    public String[] split(String regex) {
        return split(regex, 0);
    }
    public String[] split(String regex, int limit) {
        char ch = 0;
        if (((regex.value.length == 1 &&
             ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
             (regex.length() == 2 &&
              regex.charAt(0) == '\\' &&
              (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
              ((ch-'a')|('z'-ch)) < 0 &&
              ((ch-'A')|('Z'-ch)) < 0)) &&
            (ch < Character.MIN_HIGH_SURROGATE ||
             ch > Character.MAX_LOW_SURROGATE))
        {
            int off = 0;
            int next = 0;
            boolean limited = limit > 0;
            ArrayList<String> list = new ArrayList<>();
            while ((next = indexOf(ch, off)) != -1) {
                if (!limited || list.size() < limit - 1) {
                    list.add(substring(off, next));
                    off = next + 1;
                } else { 
                    list.add(substring(off, value.length));
                    off = value.length;
                    break;
                }
            }
            if (off == 0)
                return new String[]{this};
            if (!limited || list.size() < limit)
                list.add(substring(off, value.length));
            int resultSize = list.size();
            if (limit == 0) {
                while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
                    resultSize--;
                }
            }
            String[] result = new String[resultSize];
            return list.subList(0, resultSize).toArray(result);
        }
        return Pattern.compile(regex).split(this, limit);
    }

    public String trim() {
        int len = value.length;
        int st = 0;
        char[] val = value;   
        while ((st < len) && (val[st] <= ' ')) {//比较的是字符的阿斯卡码值
            st++;
        }
        while ((st < len) && (val[len - 1] <= ' ')) {
            len--;
        }
        return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
    }

    public String toString() {
        return this;
    }

    public char[] toCharArray() {
        char result[] = new char[value.length];
        System.arraycopy(value, 0, result, 0, value.length);
        return result;
    }

    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值