Remove leading and trailing spaces from String in Java example

Remove leading and trailing spaces from a string in Java example shows how to remove spaces from start and end of the string or trim string using various approaches.

How to remove leading and trailing spaces from a string in Java?

Consider below given string object which contains multiple spaces at the start and end of the string.

Use the trim method of the String class to remove these spaces from the string.

Output

Note:

The trim method removes ‘\u0020’ which is a white space character. However, the trim method does not remove Unicode white space character ‘\u00A0’. This character is commonly found in the HTML in the form of the   (Unicode no-break space). If you want to remove that, you can use the replaceAll method of the String class as given below.

How to remove only leading spaces?

If you want to remove only spaces from the start of the string, the trim method does not work as it will remove spaces from both sides. You can use the replaceAll method along with the regular expression pattern to remove only leading spaces. Use the “^\\s+” pattern to remove the leading spaces where

Output

How to remove only trailing spaces?

Use the “\\s+$” pattern to remove only trailing spaces from the string where

Output

Finally, if you are using the Apache Commons library, you can use the strip method of the StringUtils class to remove white spaces from both ends of the string as given below.

Output

This example is a part of the String in Java tutorial.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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