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() 参数
要替换单个字符,
oldChar-要在字符串中替换的字符
newChar-匹配的字符被替换为这个字符
replace()
方法采用以下两个参数:
要替换子字符串,
oldText-要在字符串中替换的子字符串
newText-匹配的子字符串被替换为这个字符串
replace()
方法采用以下两个参数:
replace() 返回值
replace()
方法返回一个新字符串,其中每次出现的匹配字符/文本都被新字符/文本替换。
示例 1: Java 字符串替换()字符
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 字符串替换()子字符串
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() 方法。