How to Replace Comma with Space in Java [2 ways]
1. Using replace() method
2. Using replaceAll() method
Read Also:
Let's dive deep into the topic:
How to Replace Comma with Space in Java
1. Using the String class replace() method
According to , the syntax of the String class replace() method is:
public String replace(CharSequence target, CharSequence replacement)
Using the String class replace() method to replace the comma with space in Java as shown below in the example:
public class ReplaceCommaWithSpace { public static void main(String args[]) { String givenString = "Alive,is,Awesome"; givenString = givenString.replace(",", " "); System.out.println(givenString); } }
Output:
Alive is Awesome
2. Using the String class replaceAll() method
It is identical to the String class replace() method but it takes regex as an argument.
According to , the syntax of the String class replaceAll() method is:
public String replaceAll(String regex, String replacement)
Using the String class replaceAll() method to replace the comma with space in Java as shown below in the example:
public class ReplaceCommaWithSpace2 { public static void main(String args[]) { String givenString = "Be,in,Present"; givenString = givenString.replaceAll(",", " "); System.out.println(givenString); } }
Output:
Be in Present
That's all for today. Please mention in the comments if you have any questions related to how to replace comma with space in Java with examples.