How can you use replace to replace multiple characters in Java?
In Java, you can use the replace method to replace multiple characters. The specific steps are as follows:
- Replace a character using the replace method.
String str = "Hello World!";
str = str.replace("l", "L");
System.out.println(str); // 输出:HeLLo WorLd!
- Replace multiple characters using the replace method.
String str = "Hello World!";
str = str.replace("l", "L").replace("o", "O");
System.out.println(str); // 输出:HeLLO WOrLd!
- Replace multiple characters using regular expressions.
String str = "Hello World!";
str = str.replaceAll("[lo]", "X");
System.out.println(str); // 输出:HeXX XWXXrXd!
In the third method, we utilized the replaceAll method and employed the regular expression “[lo]” to match the characters ‘l’ and ‘o’, and then replace them with ‘X’. The square brackets in the regular expression indicate a character class, allowing for the matching of multiple characters.