Java String源码解析——常用方法(二)

目录

1 startsWith:是否以目标字符串开头


1 startsWith:从源串指定下标开始,是否以目标字符串开头

1.1 源码

    // prefix 目标串
    // toffset 源串指定开始下标
    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,或者大于源串长度与目标串长度的差值,直接返回false
        if ((toffset < 0) || (toffset > value.length - pc)) {
            return false;
        }
        while (--pc >= 0) {
            // 但凡有一个字符不相等,直接返回false
            if (ta[to++] != pa[po++]) {
                return false;
            }
        }
        return true;
    }

2 endsWith:是否以目标字符串结束

2.1 源码

    // 如果理解了startsWith(),理解这就很简单了
    public boolean endsWith(String suffix) {
        return startsWith(suffix, value.length - suffix.value.length);
    }

3 matches:字符串是否匹配正则表达式

3.1 源码

    public boolean matches(String regex) {
        return Pattern.matches(regex, this);
    }

3.2 Pattern.matches方法实际上是使用了Pattern和Matcher类,这两个类比较难理解,就不往下分析了

    public static boolean matches(String regex, CharSequence input) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        return m.matches();
    }

3.3 Pattern 

    
    public static final int UNICODE_CHARACTER_CLASS = 0x100;

    public static final int UNICODE_CASE = 0x40;

    public static Pattern compile(String regex) {
        return new Pattern(regex, 0);
    }

    private Pattern(String p, int f) {
        pattern = p;
        flags = f;

        // to use UNICODE_CASE if UNICODE_CHARACTER_CLASS present
        if ((flags & UNICODE_CHARACTER_CLASS) != 0)
            flags |= UNICODE_CASE;

        // Reset group index count
        capturingGroupCount = 1;
        localCount = 0;

        if (pattern.length() > 0) {
            compile();
        } else {
            root = new Start(lastAccept);
            matchRoot = lastAccept;
        }
    }

3.3 Matcher

    public boolean matches() {
        return match(from, ENDANCHOR);
    }

    boolean match(int from, int anchor) {
        this.hitEnd = false;
        this.requireEnd = false;
        from        = from < 0 ? 0 : from;
        this.first  = from;
        this.oldLast = oldLast < 0 ? from : oldLast;
        for (int i = 0; i < groups.length; i++)
            groups[i] = -1;
        acceptMode = anchor;
        boolean result = parentPattern.matchRoot.match(this, from, text);
        if (!result)
            this.first = -1;
        this.oldLast = this.last;
        return result;
    }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值