使用replace()
方法替换字符串中所有出现的给定字符。
这是我们的字符串。
String str = "THIS IS DEMO LINE $$$ NEW LINE";
现在让我们用*替换所有出现的字符$
str.replace("$", "*")
以下是将所有出现的$替换为*的完整示例
public class Demo { public static void main(String[] args) { String str = "THIS IS DEMO LINE $$$ NEW LINE"; System.out.println("String = "+str); System.out.println("Replacing all occurrence of given character..."); System.out.println("Updated string = "+str.replace("$", "*")); }}
输出结果
String = THIS IS DEMO LINE $$$ NEW LINE Replacing all occurrence of given character... Updated string = THIS IS DEMO LINE *** NEW LINE