This article will illustrate the method to replace single or multiple characters in a string using Java.
How to Replace Multiple Characters in a String in Java?
For replacing several characters in a string in Java, users can use the “String.replaceAll()” method. It allows users to replace multiple characters or substrings using regular expressions.
Here are multiple examples that replace single or multiple characters in a string:
Example 1: Replace All Occurrences of a Single Character
In this example, users can utilize the “replace()” method to replace all occurrences of the character ‘o’ with the ‘*’ character in the “Hello, World!”:
Output
The output shows that all occurrences of the character ‘o’ have been replaced with the ‘*’ character.
Important: The replaceAll() method returns a new string and will not change the actual string.
Example 2: Replace all Occurrences of Multiple Characters
In this example, users can replace all happenings of vowels in the original string using a regular expression. Let us execute the below code:
In the above code, the “[]” square brackets denote a character class, and any character such as “aeiou” within the brackets is matched. The * character is used to replace each matched character.
Output
The resulting string shows that multiple characters have been replaced successfully.
Example 3: Replace Multiple Characters with Different Characters
Users can utilize two replace() methods to perform replacements with different characters. Let us conduct an example:
In this example, replace all happenings of the word ‘fox‘ with the word ‘cat‘ and all presence of the ‘dog’ with ‘cat’.
Output
The resulting string replaces all multiple characters in a string.
Conclusion
To replace multiple characters in a string, use “replaceAll()” or “replace()” methods in Java. They allow users to replace single or multiple characters or substrings using regular expressions. It is important to consider the performance implications of each method, as some may be more efficient than others for large strings or frequent replacements.