字符串.replace(String oldChar, String newChar)其中,oldChar 表示被替换的字符串;newChar 表示用于替换的字符串。replace() 方法会将字符串中所有 oldChar 替换成 newChar。
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","你好 "));
words = "hr's dog";
System.out.println("原始字符串是'"+words+"'");
System.out.println("replace(\"r's\",\"is\")结果:"+words.replace("r's","is"));
}
输出结果如下所示:
原始字符串是'hello java,hello php'
replace("l","D")结果:heDDo java,heDDo php
replace("hello","你好")结果:你好 java,你好 php
原始字符串是'hr's dog'
replace("r's","is")结果:his dog
字符串.replaceFirst(String regex, String replacement)其中,regex 表示正则表达式;replacement 表示用于替换的字符串。例如:
String words = "hello java,hello php";
String newStr = words.replaceFirst("hello","你好 ");
System.out.println(newStr); // 输出:你好 java,hello php
字符串.replaceAll(String regex, String replacement)其中,regex 表示正则表达式,replacement 表示用于替换的字符串。例如:
String words = "hello java,hello php";
String newStr = words.replaceAll("hello","你好 ");
System.out.println(newStr); // 输出:你好 java,你好 php
注意:关于正则表达式的内容会在本章的最后几节讲解,在这里了解如何操作就可以了。
可直接点击《Java字符串替换实例》一节进行巩固练习。
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有