字符串替换
replace()
replace() 方法通过用 newChar 字符替换字符串中出现的所有 searchChar 字符,并返回替换后的新字符串。
语法
public String replace(char searchChar, char newChar)
参数
- searchChar – 原字符。
- newChar – 新字符。
返回值
替换后生成的新字符串。
实例
以下实例对字符串 Runoob 中的字符进行替换:
public class Main {
public static void main(String args[]) {
String Str = "hello";
System.out.println(Str.replace('o', 'T'));
System.out.println(Str.replace('l', 'D'));
}
}
以上程序执行结果为:
hellT
heDDo
源码
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = value.length;
int i = -1;
char[] val = value; /* avoid getfield opcode */
while (++i < len) {
if (val[i] == oldChar) {//找到第一个替换的位置
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0; j < i; j++) {
buf[j] = val[j];//保存位置i之前的字符
}
while (i < len) {
char c = val[i];
buf[i] = (c == oldChar) ? newChar : c;//替换位置i以后字符
i++;
}
return new String(buf, true);
}
}
return this;
}
replaceAll
replaceAll() 方法使用给定的参数 replacement 替换字符串所有匹配给定的正则表达式的子字符串。
语法
public String replaceAll(String regex, String replacement)
参数
- regex – 匹配此字符串的正则表达式。
- replacement – 用来替换每个匹配项的字符串。
返回值
成功则返回替换的字符串,失败则返回原始字符串。
实例
String str ="www.google.com";
System.out.println(str.replaceAll("(.*)google(.*)", "baidu" ));//baidu
System.out.println(str.replaceAll("(.*)taobao(.*)", "baidu" ));//www.google.com
源码
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
采用Pattern进行替换
replaceFirst
replaceFirst() 方法使用给定的参数 replacement 替换字符串第一个匹配给定的正则表达式的子字符串。
用法同replaceAll