Replace all occurrences of a character in String in Java
This post will discuss how to replace all occurrences of a character in string with another character in Java.
1. Using String.replace() method
The standard solution to replace all occurrences of a character in the String with another is with the String.replace() method. Its usage is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 |
public class Main { public static void main(String[] args) { String str = "A|B|C|D|E"; char ch = '|'; str = str.replace(ch, ','); System.out.println(str); } } |
Output:
A,B,C,D,E
If you need to replace each occurrence of a substring in the string with another string, you can use the String.replaceAll() method:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
public class Main { public static void main(String[] args) { String str = "A|B|C|D|E"; String regex = "\\|"; String replacement = ", "; str = str.replaceAll(regex, replacement); System.out.println(str); } } |
Output:
A, B, C, D, E
2. Using StringUtils.replaceChars() method
If you use the Apache Commons Lang library in your project, consider using the StringUtils.replaceChars() method, which is a null-safe version of the String.replace() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import org.apache.commons.lang3.StringUtils; public class Main { public static void main(String[] args) { String str = "A|B|C|D|E"; char ch = '|'; str = StringUtils.replaceChars(str, ch, ','); System.out.println(str); } } |
Output:
A,B,C,D,E
That’s all about replacing all occurrences of a character in string in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)