在Java中,String 类提供了 3 种字符串替换方法,分别是 replace()、replaceFirst() 和 replaceAll(),下面我们就来详细看一下三种的用法!
replace() 方法
replace() 方法用于将目标字符串中的指定字符(串)替换成新的字符(串),其语法格式如下:
字符串.replace(String oldChar, String newChar)
其中,oldChar 表示被替换的字符串;newChar 表示用于替换的字符串。replace() 方法会将字符串中所有 oldChar 替换成 newChar。
例 1:
创建一个字符串,对它使用 replace() 方法进行字符串替换并输出结果。代码如下:
public static void main(String[] args) {
String words = "hello java,hello php";
System.out.println("原始字符串是'"+words+"'");
System.out.println("replace(\"l\",\"D\")结果:"+words.replace("l","D"));
System.out.println("replace(\"hello\",\"你好\")结果:"+words.replace("hello","你好 "