1.使用replace()
public class Test{
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"));
words="hr's dog";
System.out.println("源字符串是:"+words);
System.out.println("replace(\"r's\",\"is\")结果:"+words.replace("r's","is"));
}
}
2.使用replaceFirst()
String words="hello java,hello,php";
String news=words.replaceFirst("hello", "你好");
System.out.println(news);
3.使用replaceAll()
String words="hello java,hello,php";
String news=words.replaceAll("hello", "你好");
System.out.println(news);

本文介绍了Java中三种不同的字符串替换方法:replace(), replaceFirst() 和replaceAll()。通过具体示例展示了如何使用这些方法来替换字符串中的特定字符或子串。
1518

被折叠的 条评论
为什么被折叠?



