English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java String replace()方法用 新的字符/文本 替换 字符串中每个匹配的旧字符/文本。
replace()方法的语法是
string.replace(char oldChar, char newChar)
或
string.replace(CharSequence oldText, CharSequence newText)
要替换单个字符,replace()方法采用以下两个参数:
oldChar - 字符串中要替换的字符
newChar - 匹配的字符被替换为该字符
要替换子字符串,replace()方法采用以下两个参数:
oldText - 字符串中要替换的子字符串
newText - 匹配的子字符串被替换为该字符串
replace()方法返回一个新字符串,其中每次出现的匹配字符/文本都将替换为新字符/文本。
class Main { public static void main(String[] args) { String str1 = "abc cba" //所有出现的" a"都替换为" z" System.out.println(str1.replace('a', 'z')); // zbc cbz //所有出现的" L"都替换为" J" System.out.println("Lava".replace('L', 'J')); // Java //字符不在字符串中 System.out.println("Hello".replace('4', 'J')); // Hello } }
Note:如果要替换的字符不在字符串中,则replace()返回原始字符串。
class Main { public static void main(String[] args) { String str1 = "C++ Programming"; //所有出现的"c++")都被替换为"Java" System.out.println(str1.replace("C", "++", "Java")); // Java Programming //All occurrences of "a" are replaced with "zz" System.out.println("aa bb aa zz".replace("aa", "zz")); // zz bb aa zz // The substring is not in the string System.out.println("Java".replace("C++", "C"); // Java } }
Note:If the substring to be replaced is not in the string, then replace() returns the original string.
It should be noted that the replace() method replaces the substring from the beginning to the end. For example,
"zzz".replace("zz", "x") // xz
The output of the above code is xz, not zx. This is because the replace() method replaces the first zz with x
If you need to replace a substring based on a regular expression, please useJava String replaceAll() Method.