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:

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:

Output:

This_blog_is_Java2blog

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

Output:

_This_blog_is_Java2blog_

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

Output:

This_blog_is_Java2blog

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

Was this post helpful?

Leave a Reply

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