replace()
方法将字符串中的每个匹配的字符/文本替换为新的字符/文本。
示例
class Main {
public static void main(String[] args) {
String str1 = "bat ball";
// replace b with c
System.out.println(str1.replace('b', 'c'));
}
}
// Output: cat call
replace() 语法
replace()
方法的语法是:
string.replace(char oldChar, char newChar)
或者
string.replace(CharSequence oldText, CharSequence newText)
这里,string是String
类的一个对象。
replace() 参数
要替换单个字符,replace()
方法接受这两个参数:
- oldChar - 要在字符串中替换的字符
- newChar - 匹配的字符将被替换为此字符
要替换子字符串,replace()
方法接受这两个参数:
- oldText - 要在字符串中替换的子字符串
- newText - 匹配的子字符串将被替换为此字符串
replace() 返回值
replace()
方法返回一个新字符串,其中匹配的字符/文本的每个出现都已被替换为新的字符/文本。
示例 1:Java String replace() 字符
class Main {
public static void main(String[] args) {
String str1 = "abc cba";
// all occurrences of 'a' is replaced with 'z'
System.out.println(str1.replace('a', 'z')); // zbc cbz
// all occurences of 'L' is replaced with 'J'
System.out.println("Lava".replace('L', 'J')); // Java
// character not in the string
System.out.println("Hello".replace('4', 'J')); // Hello
}
}
注意:如果要在字符串中替换的字符不存在,replace()
将返回原始字符串。
示例 2:Java String replace() 子字符串
class Main {
public static void main(String[] args) {
String str1 = "C++ Programming";
// all occurrences of "C++" is replaced with "Java"
System.out.println(str1.replace("C++", "Java")); // Java Programming
// all occurences of "aa" is replaced with "zz"
System.out.println("aa bb aa zz".replace("aa", "zz")); // zz bb zz zz
// substring not in the string
System.out.println("Java".replace("C++", "C")); // Java
}
}
注意:如果要在字符串中替换的子字符串不存在,replace()
将返回原始字符串。
需要注意的是,replace()
方法会从头到尾替换子字符串。例如:
"zzz".replace("zz", "x") // xz
上述代码的输出是 xz,而不是 zx。这是因为replace()
方法将第一个 zz 替换为了 x。
如果您需要根据正则表达式替换子字符串,请使用Java String replaceAll() 方法。
另请阅读