Java中的字符替换


在JDK的String类中,提供了replace、relaceAll、replaceFirst三个方法用于字符替换,其中replaceFirst通过字面理解就是替换匹配的第一个字符;而replace、relaceAll都是全部替换的意思

那这三个有什么本质上的区别呢??

下面看一个例子,需要将字符串"orange.peach.banana.tomato"中的所有"."替换为"|",

package com.yf.str;

public class ReplaceStr {

 public static void main(String[] args) {
  String str="orange.peach.banana.tomato";
  System.out.println(str.replace(".", "|"));
  System.out.println(str.replaceAll(".", "|"));
  System.out.println(str.replaceFirst(".", "|"));
 }

}

输出结果如下

orange|peach|banana|tomato
||||||||||||||||||||||||||
|range.peach.banana.tomato

从结果可以看出,第一个是我们想要的结果,而后面两个都不是我们预期的答案,这是为什么呢??

看看String类中源码实现:

首先看看replace的实现(已经通过注释解答逻辑)

 public String replace(char oldChar, char newChar) {
 if (oldChar != newChar) {
    int len = count;
    int i = -1;
    char[] val = value; /* avoid getfield opcode */
    int off = offset;  /* avoid getfield opcode */
   
    //找到第一个需要替换字符的位置
    while (++i < len) {
  if (val[off + i] == oldChar) {
      break;
  }
    }
    //将第一个需要替换的字符前面部分拷贝出来
    if (i < len) {
  char buf[] = new char[len];
  for (int j = 0 ; j < i ; j++) {
      buf[j] = val[off+j];
  }
  //从第一个需要替换的字符开始,替换后面所有的字符
  while (i < len) {
      char c = val[off + i];
      buf[i] = (c == oldChar) ? newChar : c;
      i++;
  }
  //返回新的字符串
  return new String(0, len, buf);
    }
 }
 return this;
    }

很明显,replace直接就是要字符匹配,相当于匹配ASSIC码,它遍历字符数组中的每一个元素,判断字符是否与'.'相等,如果相等则替换,所以它能将字符串里面所有的"."全部替换为"|"。

再看看replaceAll的逻辑

public String replaceAll(String regex, String replacement) {
     //解析正则表达式,然后替换匹配的正则
 return Pattern.compile(regex).matcher(this).replaceAll(replacement);
    }

replaceAll与replace本质区别在于其是用正则的方式匹配,它传入的是一个正则表达式,而在正则表达式中"."表示的任意字符,所以上面调用replaceAll后会将所有字符都替换为"|"。那么很容易推测出replaceFirst也是通过正则匹配,而实际上它也确实这么做的

public String replaceFirst(String regex, String replacement) {
 return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
    }

那么上面的代码的正确方式是将replaceAll、replaceFirst的输入转义,转为真正的"."

String str="orange.peach.banana.tomato";
System.out.println(str.replace(".", "|"));
System.out.println(str.replaceAll("\\.", "|"));
System.out.println(str.replaceFirst("\\.", "|"));

输出结果如下:

orange|peach|banana|tomato
orange|peach|banana|tomato
orange|peach.banana.tomato

需要注意一下String.split(String regex)、String.matches(String regex)等都是通过正则匹配来做判断的(只有replace通过判断字符是否相等)

相关内容

    暂无相关文章