In the development, we will encounter the need to remove about space needs, if only a simple spaces, adjustment to the trim () method can be, but if there are Chinese full-width, carriage return appears to be non-blank spaces, you need to customize to achieve development, this tool can achieve the following about those who seem to be space for all space characters.
import com.google.common.base.CharMatcher; /** * @author yangzhilong * @date 6/25/2019 * / Public class TrimUtils { / ** * trim left and right char to "",chars like tab/chinese space/enter/english space * @return */ public static String trimAnyBlank(String str) { if(null != str) { return CharMatcher.anyOf("\r\n\t \u00A0 ").trimFrom(str); } return str; } }
unit test:
import static org.junit.Assert.assertEquals; import org.junit.Test; /** * @author yangzhilong * @date 6/25/2019 * / Public class TrimUtilsTest { @Test public void testTrim () { // around each of the spaces in the whole angle String STR = "XFD" ; int length = TrimUtils.trimAnyBlank (STR) .length (); assertEquals(length, 3); } }