String 类的 replace 和 replaceAll 方法源码分析

在解决剑指Offer的面试题的时候,有一题讲的是替换字符串,作者给出的解决办法是使用数组复制的方式。如果不考虑是算法题的话,我们可以使用String类的replace() 和 replaceAll() 来解决字符串替换的需求,那么这两个方法的的底层实现是什么样子的呢?

首先我们根据源码中的注释可以了解到,replace这个方法适用于用指定的文字替换序列替换与文字目标序列匹配的字符串的每个子字符串, 而replaceAll这个方法则适用于将与给定正则表达式匹配的字符串的每个子字符串替换为给定的替换。

    /**
     * Replaces each substring of this string that matches the literal target
     * sequence with the specified literal replacement sequence. The
     * replacement proceeds from the beginning of the string to the end, for
     * example, replacing "aa" with "b" in the string "aaa" will result in
     * "ba" rather than "ab".
     */
    public String replace(CharSequence target, CharSequence replacement) {
        return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
                this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
    }

    /**
     * Replaces each substring of this string that matches the given <a
     * href="../util/regex/Pattern.html#sum">regular expression</a> with the
     * given replacement.
     */
    public String replaceAll(String regex, String replacement) {
        return Pattern.compile(regex).matcher(this).replaceAll(replacement);
    }

通过方法的定义,可以直接了当的看到:
replaceAll() 在定义它的时候,就被赋予可以匹配正则表达式的功能。

通过源码,也可以看到两点:

  1. String.replace() 和 String.replaceAll() 调用的方法是一样的,都是Matcher.replaceAl
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值