Java String replace()方法
String.replace() API 用于搜索一个字面子字符串,并将每个出现的子字符串替换为指定的替换字符串。搜索子字符串的起始位置从字符串的开头开始,即索引0。
需要注意的是,类似的方法 String.replaceAll() 使用正则表达式搜索和替换所有子字符串。
1.String.replace() API
replace() 方法有两个重载版本:
public String replace(char oldChar, char newChar); public String replace(CharSequence target, CharSequence replacement);
第一个方法接受 char 类型的参数。它在字符串中搜索指定的 oldChar,并将每个出现的 oldChar 替换为 newChar。
第二个方法接受 String 类型的参数。它在字符串中搜索指定的目标子字符串,并将每个出现的子字符串替换为指定的替换字符串。
2.使用 String.replace() 替换字符
以下Java程序将所有出现的小写字母 ‘o’ 替换为大写字母 ‘O’。
String message = "Hello world !!"; Assertions.assertEquals("HellO wOrld !!", message.replace('o', 'O'));
3.使用 String.replace() 替换子字符串
以下Java程序将所有出现的子字符串 “Hello” 替换为新的字符串 “Hi”。
String message = "Hello world !!"; Assertions.assertEquals("Hi world !!", message.replace("Hello", "Hi"));
4.不支持正则表达式
不允许将正则表达式作为方法参数。如果我们使用正则表达式模式,它将被视为普通字符串。
在下面的程序中,如果支持正则表达式,正则表达式模式 [H] 会匹配字符 H。但是 replace() 不支持正则表达式,因此找不到匹配项。
String message = "Hello world !!"; Assertions.assertEquals("Hello world !!", message.replace("[H]", "h"));
5.>null不允许作为方法的两个参数
这会引发 NullPointerException(空指针异常)。所以,在使用 String.replace()
方法时,请确保参数不为 null
。
Assertions.assertThrows(NullPointerException.class, () -> { message.replace(null, "O"); }); Assertions.assertThrows(NullPointerException.class, () -> { message.replace("o", null); });