To replace a specific string or character in a string in Java, you can use the replace
or replaceAll
method of the String
class.
The replace
method replaces all occurrences of a specific character with another character. Here's an example:
String s = "Hello World"; String s2 = s.replace('o', '0'); // s2 is "Hell0 W0rld"
The replaceAll
method replaces all occurrences of a specific string with another string. It takes a regular expression (regex) as the first argument and the replacement string as the second argument. Here's an example:
String s = "Hello World"; String s2 = s.replaceAll("l", "L"); // s2 is "HeLLo WorLd"
You can also use the replaceFirst
method, which works like replaceAll
, but only replaces the first occurrence of the specified string.
It's important to note that these methods return a new string, and do not modify the original string. If you want to update the original string, you will need to reassign it to the result of the replace
or replaceAll
method.
Here's an example of how you could use these methods to replace multiple strings in a single line of code:
String s = "Hello World"; String s2 = s.replace('o', '0').replaceAll("l", "L").replaceFirst("H", "h"); // s2 is "heLL0 WorLd"
You can find more information about these methods and examples of how to use them in the Java documentation.