StringUtils依赖于commons-lang3这个jar
(1)空字符串检查
public static boolean isBlank(CharSequence cs)
源码:
public static boolean isBlank(CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
可以看出,实际上就是先判断是否==null和长度是否等于0,再判断是不是全部都是空格。
(2)去除开始和结尾的空字符
public static boolean isBlank(CharSequence cs)
举例:
@Test
public void test()
{
String test1 = "\t";
String test2 = " A Test ";
String test3 = null;
System.out.println(StringUtils.trimToNull( test1 ) );
System.out.println(StringUtils.trimToNull( test2 ) );
System.out.println(StringUtils.trimToNull( test3 ) );
}
结果为:
null
A Test
null
(3)颠倒字符串
String StringUtils.reverse(String str)
例子:
@Test
public void test()
{
System.out.println( StringUtils.reverse("ABCDE"));
}
结果为:
EDCBA
(4)判断字符串内容的类型
boolean StringUtils.isNumeric(CharSequence cs) //是否全由数字组成
boolean StringUtils.isAlpha(CharSequence cs) //是否全由字母组成
boolean StringUtils.isAlphanumeric(CharSequence cs) //是否全由字母或数字组成
boolean StringUtils.isAlphaSpace(CharSequence cs) //是否全由字母或空格组成
例子:
@Test
public void test()
{
String state = "Virginia";
System.out.println( "Is state number? " + StringUtils.isNumeric(state ) );
System.out.println( "Is state alpha? " + StringUtils.isAlpha( state ));
System.out.println( "Is state alphanumeric? " +StringUtils.isAlphanumeric( state ) );
System.out.println( "Is state alphaspace? " + StringUtils.isAlphaSpace( state ) );
}
结果为:
Is state number? false
Is state alpha? true
Is state alphanumeric? true
Is state alphaspace? true