How to Replace Comma with Space in Java [2 ways]

In this post, I will be sharing how to replace comma with space in Java with examples. There are two ways to achieve our goal of replacing comma with space in Java:

1. Using replace() method

2. Using replaceAll() method

Read Also: Replace space with underscore in Java

Let's dive deep into the topic:

How to Replace Comma with Space in Java

1. Using the String class replace() method


According to Oracle docs, 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 Oracle docs, 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.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry