How to replace multiple characters in a JAVA string?
In Java, you can use the replace() method of the String class to replace multiple characters. There are two forms of this method:
- replace a single character:
String str = "Hello World";
String newStr = str.replace('o', 'a');
System.out.println(newStr); // 输出:Hella Warld
- Replace multiple characters.
String str = "Hello World";
String newStr = str.replace("o", "a").replace("l", "b");
System.out.println(newStr); // 输出:Hebba Warbd
In the second form, you can use the replace() method repeatedly to substitute multiple characters one after another. Keep in mind that each time you call the replace() method, it will return a new string without changing the original string.