在解决剑指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() 在定义它的时候,就被赋予可以匹配正则表达式的功能。
通过源码,也可以看到两点:
- String.replace() 和 String.replaceAll() 调用的方法是一样的,都是Matcher.replaceAl