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.
1 |
String str = " string with white spaces "; |
Use the trim
method of the String class to remove these spaces from the string.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.javacodeexamples.stringexamples; public class StringTrimExample { public static void main(String[] args) { String str = " string with white spaces "; str = str.trim(); System.out.println(str); } } |
Output
1 |
string with white spaces |
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.
1 |
String str = str.replaceAll("\\u00A0", ""); |
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
1 2 3 |
^ - means start of the string \\s - matches space characters + - one or more |
1 2 3 4 5 |
String str = " string with white spaces "; str = str.replaceAll("^\\s+", ""); System.out.println("\"" + str + "\""); |
Output
1 |
"string with white spaces " |
How to remove only trailing spaces?
Use the “\\s+$” pattern to remove only trailing spaces from the string where
1 2 3 |
\\s - matches space character + - one or more $ - end of the string |
1 2 3 4 5 |
String str = " string with white spaces "; str = str.replaceAll("\\s+$", ""); System.out.println("\"" + str + "\""); |
Output
1 |
" string with white spaces" |
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.
1 2 3 4 5 |
String str = " string with white spaces "; str = StringUtils.strip(str); System.out.println("\"" + str + "\""); |
Output
1 |
"string with white spaces" |
This example is a part of the String in Java tutorial.
Please let me know your views in the comments section below.