Table of Contents
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:
1 2 3 |
public String replace(CharSequence target, CharSequence replacement) |
1 2 3 4 5 6 7 8 9 10 11 12 |
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:
1 2 3 |
public String replaceAll(String regex, String replacement) |
1 2 3 4 5 6 7 8 9 10 11 |
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
Further reading:
That’s all about how to replace comma with space in java.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.