21. Removing leading and trailing spaces

The quickest solution to this problem probably relies on the String.trim() method. This method is capable of removing all leading and trailing spaces, that is, any character whose code point is less than or equal to U+0020 or 32 (the space character):

String text = "
 

 hello 	 
 
";
String trimmed = text.trim();

The preceding snippet of code will work as expected. The trimmed string will be hello. This only works because all of the white spaces that are being used are less than U+0020 or 32 (the space character). There are 25 characters (https://en.wikipedia.org/wiki/Whitespace_character#Unicode) defined as white spaces and trim() covers only a part of them (in short, trim() is not Unicode aware). Let's consider the following string:

char space = 'u2002';
String text = space + " hello " + space;

u2002 is another type of white space that trim() doesn't recognize (u2002 is above u0020). This means that, in such cases, trim() will not work as expected. Starting with JDK 11, this problem has a solution named strip(). This method extends the power of trim() into the land of Unicode:

String stripped = text.strip();

This time, all of the leading and trailing white spaces are removed.

Moreover, JDK 11 comes with two flavors of strip() for removing only the leading (stripLeading()) or only the trailing (stripTrailing()) white spaces. The trim() method doesn't have these flavors.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.170.187