How to Replace Space with Underscore in Java

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:

public String replace(CharSequence target, CharSequence replacement)  
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:

This_blog_is_Java2blog

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:

public String replaceAll(String regex, String replacement)  
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:

This_blog_is_Java2blog

If you want to replace consecutive spaces with one underscore, you can use replaceAll with regex \\s+.

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:

_This_blog_is_Java2blog_

If you don’t want first and last underscore in the output, call trim() method before calling repalceAll() method.

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:

This_blog_is_Java2blog

That’s all about how to replace space with underscore 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.