How to Replace Comma with Space in Java

Learn about how to replace comma with space in java.

Replace comma with space in java

1. Using replace() method

Use String’s replace() method to replace comma with space in java.

Here is syntax of replace() method:

public String replace(CharSequence target, CharSequence replacement)  
package org.arpit.java2blog;

public class ReplaceCommaWithSpaceMain {

    public static void main(String[] args) {
        String str = "1,2,3,4";
        str = str.replace(","," ");
        System.out.println(str);
    }
}

Output:

1 2 3 4

As you can see, replace() method replaced each comma with space in the String.

2. Using replaceAll() method

Use replaceAll() method to replace comma with space in java. It is identical to replace() method, but it takes regex as argument. You can go through difference between replace and replaceAll over here.

Here is syntax of replaceAll method:

public String replaceAll(String regex, String replacement)  
package org.arpit.java2blog;

public class ReplaceCommaWithSpaceMain {
    public static void main(String[] args) {
        String str = "1,2,3,4";
        str = str.replaceAll(","," ");
        System.out.println(str);
    }
}

Output:

1 2 3 4

That’s all about how to replace comma with space in java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.