@Test Public voidTesttrimwhitespace ()throwsException {assertequals (NULL, Stringutils.trimwhitespace (NULL)); Assertequals ("", Stringutils.trimwhitespace ("" ")); Assertequals ("", Stringutils.trimwhitespace ("" ")); Assertequals ("", Stringutils.trimwhitespace ("\ t")); Assertequals ("A", Stringutils.trimwhitespace ("a")); Assertequals ("A", Stringutils.trimwhitespace ("a")); Assertequals ("A", Stringutils.trimwhitespace ("a")); Assertequals ("A B", Stringutils.trimwhitespace ("a B")); Assertequals ("A b C", Stringutils.trimwhitespace ("a b C")); Assertequals ("A b C", Stringutils.trimwhitespace ("\r\f\n a b c \ t")); }
You can see that this method can handle
\ n Enter (\u000a)
\ t Horizontal tab (\U0009)
\ r line Break (\u000d)
\f Page Change (\u000c)
In fact, with the Java string method of trim can achieve the same function
/*** Trim leading and trailing whitespace from the given String. * @paramstr the String to check *@returnThe trimmed String *@seeJava.lang.character#iswhitespace*/ Public Staticstring Trimwhitespace (String str) {if(!haslength (str)) { returnstr; } StringBuilder SB=NewStringBuilder (str); while(Sb.length () > 0 && character.iswhitespace (Sb.charat (0)) {Sb.deletecharat (0); } while(Sb.length () > 0 && character.iswhitespace (Sb.charat (Sb.length ()-1)) {Sb.deletecharat (sb.length () ))-1); } returnsb.tostring (); }
/*** Check The given String is neither {@codenull} Nor of length 0. * Note:will return {@codetrue} for a String, that purely consists of whitespace. * @paramstr the String to check ( could be {@codenull}) * @return {@codetrue if the String is not null and have length *@see#hasLength (charsequence)*/ Public Static Booleanhaslength (String str) {returnhaslength ((charsequence) str); }
/*** Check The given charsequence is neither {@codenull} Nor of length 0. * Note:will return {@codetrue} for a charsequence that purely consists of whitespace. * <p><pre class= "code" > * STRINGUTILS.HASLENGTH (NULL) = False * Stringutils.haslength ("") = False * Stringutils.haslength ("") = True * Stringutils.haslength ("Hello") = True * </pre> *@paramstr the charsequence to check ( could be {@codenull}) * @return {@codetrue} if the charsequence is not null and have length *@see#hasText (String)*/ Public Static Booleanhaslength (charsequence str) {return(str! =NULL&& str.length () > 0); }
A method like the trim method of string in the spring framework