SpringBoot - 实用工具类库common-util使用详解3(字符串工具类:StringUtil)
SpringBoot - 实用工具类库common-util使用详解3(字符串工具类:StringUtil)
字符串工具类(StringUtil)
1,判断是否为空
(1)isEmpty()
方法可判断传入字符串是否为空,如果为空则返回 true,不为空则访问 false
StringUtil.isEmpty(null); // true
StringUtil.isEmpty(""); // true
StringUtil.isEmpty(" "); // true
StringUtil.isEmpty("NaN"); // true
StringUtil.isEmpty("null"); // true
StringUtil.isEmpty("hangge"); // false
(2) isNotEmpty()
方法用于判断字符串是否不为空,它和 isEmpty() 方法的返回结果刚好相反,如果不为空则访问 true,为空则返回 false。
StringUtil.isNotEmpty(null); // false
StringUtil.isNotEmpty(""); // false
StringUtil.isNotEmpty(" "); // false
StringUtil.isNotEmpty("NaN"); // false
StringUtil.isNotEmpty("null"); // false
StringUtil.isNotEmpty("hangge"); // true
2,驼峰与下划线格式的转换
camelToUnderline()
方法可以将驼峰格式转化成下划线格式,underlineToCamel()
方法则可以将下划线转化成驼峰格式。
StringUtil.camelToUnderline("helloWorld"); // hello_world
StringUtil.underlineToCamel("hello_world"); // helloWorld
3,去除空格
trim() 方法可去除字符串中所有空格,而 trimBlank()
方法只会去除字符串首尾部分(左右两侧)的空格。
//去除所有的空格
StringUtil.trim(" hello world "); // helloworld
//只去除字符串前后的空格
StringUtil.trimBlank(" hello world "); // hello world
4,首字母大小写
(1)firstToUpperCase()
方法用于将首字母转大写:
StringUtil.firstToUpperCase("hello"); // Hello;
(2)firstToLowerCase()
StringUtil.firstToLowerCase("HELLO"); // hELLO;
5,提取中文/非中文字符
(1)getChinese()
方法可以提取出字符串中的中文:
StringUtil.getChinese("欢迎访问 dandelioncloud.cn");//欢迎访问
(2)方法用于将字符串首字母小写:
(1) getNotChinese()
方法用于提取字符串中非中文字符(只提取英文和数字):
StringUtil.getNotChinese("欢迎访问 dandelioncloud.cn");//dandelioncloud
6,数字转字符串,前面补 0
seqNumLeftPadZero()
方法一般用于创建一个流水号,位数不够时自动用 0 来补位(如果超过指定位数则不变):
String str1 = StringUtil.seqNumLeftPadZero(1, 4);
String str2 = StringUtil.seqNumLeftPadZero(22, 4);
String str3 = StringUtil.seqNumLeftPadZero(333, 4);
String str4 = StringUtil.seqNumLeftPadZero(55555, 4);
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
还没有评论,来说两句吧...