replace()
String 类提供了两个 replace() 方法,这是最常用、最直接的替换方式。

replace(char oldChar, char newChar)
功能:将字符串中所有出现的 oldChar 字符替换为 newChar 字符。
特点:
- 区分大小写:'A' 和 'a' 是不同的字符。
- 全局替换:会替换字符串中所有匹配的字符,而不仅仅是第一个。
示例:
public class ReplaceExample {
public static void main(String[] args) {
String str = "hello world, hello java";
// 将所有 'l' 替换为 'p'
String newStr = str.replace('l', 'p');
System.out.println("原始字符串: " + str);
System.out.println("替换后字符串: " + newStr); // 输出: heppo worpd, heppo java
}
}
replace(CharSequence target, CharSequence replacement)
功能:将字符串中所有出现的 target 子串替换为 replacement 子串。

特点:
- 替换子串:可以替换任意长度的子串,而不仅仅是单个字符。
- 区分大小写:同样区分大小写。
- 全局替换:替换所有匹配的子串。
CharSequence是一个接口,String、StringBuilder、CharBuffer等都实现了它,所以可以直接传入String对象。
示例:
public class ReplaceSubstringExample {
public static void main(String[] args) {
String str = "I like Java, and Java is powerful.";
// 将所有 "Java" 替换为 "Python"
String newStr = str.replace("Java", "Python");
System.out.println("原始字符串: " + str);
System.out.println("替换后字符串: " + newStr); // 输出: I like Python, and Python is powerful.
}
}
其他重要替换方法
除了 replace(),还有其他方法可以提供更灵活的控制,比如只替换第一个匹配项,或者使用正则表达式进行复杂的匹配和替换。
replaceFirst(String regex, String replacement)
功能:使用给定的 正则表达式 regex 替换 第一个 匹配的子串。
特点:
- 基于正则表达式:
regex参数是一个正则表达式,这意味着你可以用它进行更复杂的匹配(匹配数字、特定模式的字符串等)。 - 仅替换第一个:只替换第一个找到的匹配项。
示例:
public class ReplaceFirstExample {
public static void main(String[] args) {
String str = "apple orange apple banana";
// 将第一个 "apple" 替换为 "grape"
String newStr1 = str.replaceFirst("apple", "grape");
System.out.println(newStr1); // 输出: grape orange apple banana
// 使用正则表达式,将第一个单词(由空格分隔)替换为 "fruit"
String newStr2 = str.replaceFirst("\\w+", "fruit");
System.out.println(newStr2); // 输出: fruit orange apple banana
}
}
replaceAll(String regex, String replacement)
功能:使用给定的 正则表达式 regex 替换 所有 匹配的子串。
特点:
- 基于正则表达式:功能非常强大,可以处理复杂的文本匹配模式。
- 全局替换:替换所有匹配项。
- 注意:这个方法经常与
replace()混淆,当你的替换目标是固定的字符串(而不是正则表达式模式)时,优先使用replace(),因为它更直观且性能略好。
示例:
public class ReplaceAllExample {
public static void main(String[] args) {
String str = "My phone number is 123-456-7890, and my friend's is 987-654-3210.";
// 将所有连字符 '-' 替换为空格 ' '
// 注意:这里用 replace("-"," ") 更简单,但 replaceAll 也能做到
String newStr1 = str.replaceAll("-", " ");
System.out.println(newStr1); // 输出: My phone number is 123 456 7890, and my friend's is 987 654 3210.
// 使用正则表达式,移除所有非数字字符
String newStr2 = str.replaceAll("\\D", "");
System.out.println(newStr2); // 输出: 12345678909876543210
}
}
特殊情况:替换正则表达式中的特殊字符
如果你想要替换的字符串本身包含正则表达式中的特殊字符(如 , , 等),直接使用 replaceAll 会导致错误,你需要使用 Matcher.quoteReplacement() 来对这些特殊字符进行转义。
示例:
public class ReplaceSpecialCharExample {
public static void main(String[] args) {
String price = "The price is $100.50.";
// 错误示范:"$" 在正则中有特殊含义(行尾),会抛出异常
// String wrongResult = price.replaceAll("$", "USD ");
// 正确做法:使用 Matcher.quoteReplacement() 对替换字符串进行转义
String correctResult = price.replaceAll("\\$", Matcher.quoteReplacement("USD "));
System.out.println(correctResult); // 输出: The price is USD 100.50.
}
}
StringBuilder 中的替换方法
当你需要在一个循环中频繁修改字符串时,应该使用 StringBuilder 或 StringBuffer,因为它们是可变的,性能远优于 String 的不可变性。
StringBuilder 也有 replace() 方法,但它的签名和 String 的不同:
StringBuilder replace(int start, int end, String str)
功能:用 str 字符串替换当前 StringBuilder 中从 start (包含) 到 end (不包含) 位置的字符。
特点:
- 基于索引:通过指定起始和结束索引来定位要替换的区域。
- 原地修改:直接修改
StringBuilder对象本身,并返回this。
示例:
public class StringBuilderReplaceExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello, World!");
// 将索引 7 到 12 的子串 "World" 替换为 "Java"
sb.replace(7, 12, "Java");
System.out.println(sb.toString()); // 输出: Hello, Java!
}
}
总结与对比
| 方法 | 功能 | 是否区分大小写 | 替换单个字符/子串 | 是否基于正则表达式 | 替换范围 |
|---|---|---|---|---|---|
replace(char, char) |
替换所有指定字符 | 是 | 单个字符 | 否 | 全局 |
replace(CharSequence, CharSequence) |
替换所有指定子串 | 是 | 子串 | 否 | 全局 |
replaceFirst(String, String) |
替换第一个匹配的子串 | 是 | 子串 | 是 | 仅第一个 |
replaceAll(String, String) |
替换所有匹配的子串 | 是 | 子串 | 是 | 全局 |
StringBuilder.replace() |
替换指定索引区间的字符 | 是 | 子串 | 否 | 指定索引区间 |
如何选择?
-
简单替换固定字符/子串:
- 用
String.replace(),这是最简单、最安全的选择。 str.replace("old", "new")
- 用
-
需要替换第一个匹配项:
- 用
String.replaceFirst()。 str.replaceFirst("\\d+", "one")(将第一个数字替换为 "one")
- 用
-
需要根据复杂模式(正则表达式)进行全局替换:
- 用
String.replaceAll()。 str.replaceAll("\\s+", " ")(将所有空白字符替换为一个空格)
- 用
-
在循环中或需要高性能地构建和修改字符串:
- 使用
StringBuilder,并在构建完成后通过toString()转换为String,如果替换的是固定索引区间的内容,就用StringBuilder.replace()。
- 使用
-
*替换的字符串包含正则元字符(如 , ``)**:
- 使用
replaceAll时,务必用Matcher.quoteReplacement()对替换字符串进行转义。str.replaceAll("\\$", Matcher.quoteReplacement("USD "))。
- 使用
