Learn to use String
class’s strip()
, stripLeading()
and stripTrailing()
methods to remove unwanted white spaces from a given string in Java 11.
1. Using String strip() APIs – Java 11
Since Java 11, String
class includes 3 more methods that help in removing extra white spaces. These methods use Character.isWhitespace(char) method to determine a white space character.
- String strip() – returns a string whose value is given string, with all leading and trailing white space removed. Please note that
String.trim()
method also produces the same result. - String stripLeading() – returns a string whose value is given string, with all leading white space removed.
- String stripTrailing() – returns a string whose value is given string, with all trailing white space removed.
String str = " Hello World !! "; System.out.println( str.strip() ); //"Hello World !!" System.out.println( str.stripLeading() ); //"Hello World !! " System.out.println( str.stripTrailing() ); //" Hello World !!"
See Also: Removing Leading Spaces and Removing Trailing Spaces from a String
2. Using Regex
If you are not using Java 11 then you can use regular expressions to trim the white spaces (including tabs) around a string.
Regular expression | Description |
---|---|
^[ \t]+|[ \t]+$ | Remove leading and trailing white spaces |
^[ \t]+ | Remove only leading white spaces |
[ \t]+$ | Remove only trailing white spaces |
String str = " Hello World !! ";
System.out.println( str.replaceAll("^[ \t]+|[ \t]+$", "") ); //"Hello World !!"
System.out.println( str.replaceAll("^[ \t]+", "") ); //"Hello World !! "
System.out.println( str.replaceAll("[ \t]+$", "") ); //" Hello World !!"
Drop me your questions related to how to remove white spaces and tabs from a string in Java.
Happy Learning !!
Leave a Reply