Table of Contents
Learn about how to replace space with underscore in java.
Replace space with underscore in java
1. Using replace() method
Use String’s replace()
method to replace space with underscore in java.
String’s replace()
method returns a string replacing all the CharSequence to CharSequence.
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 ReplaceSpaceWithUnderscoreMain { public static void main(String[] args) { String str = "This blog is Java2blog"; str = str.replace(" ","_"); System.out.println(str); } } |
Output:
As you can see, replace() method replaceed each space with underscore.
2. Using replaceAll()
method
Use replaceAll()
method to replace space with underscore 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 ReplaceSpaceWithUnderscoreMain { public static void main(String[] args) { String str = "This blog is Java2blog"; str = str.replaceAll(" ","_"); System.out.println(str); } } |
Output:
If you want to replace consecutive spaces with one underscore, you can use replaceAll with regex \\s+
.
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class ReplaceMultipleSpacesWithUnderscoreMain { public static void main(String[] args) { String str = " This blog is Java2blog "; str = str.replaceAll("\\s+","_"); System.out.println(str); } } |
Output:
If you don’t want first and last underscore in the output, call trim()
method before calling repalceAll()
method.
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class ReplaceMultipleSpacesWithUnderscoreMain { public static void main(String[] args) { String str = " This blog is Java2blog "; str = str.trim().replaceAll("\\s+","_"); System.out.println(str); } } |
Output:
Further reading:
That’s all about how to replace space with underscore in java.