一、导入字符串工具类Maven依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
org.apache.commons.lang3.StringUtils(Apache Commons Lang)和 org.springframework.util.StringUtils(Spring Framework)是两种不同的字符串工具类,功能有部分重叠,前者提供 100+ 方法,覆盖字符串的空值检查、截取、拼接、转换、比较、格式化等。功能更全面。
二、StringUtils.isEmpty()
作用是判断是否为空.。空格,并不是严格的空值
package com.example.springboottest;
import org.apache.commons.lang3.StringUtils;
public class Test {
public static void main(String[] args) {
System.out.println(StringUtils.isEmpty(null));//true
System.out.println(StringUtils.isEmpty(""));//true
System.out.println(StringUtils.isEmpty(" "));//false
}
}
ctrl+B溯源查看底层源码
三、StringUtils.isBlank()
空格也为true
package com.example.springboottest;
import org.apache.commons.lang3.StringUtils;
public class Test {
public static void main(String[] args) {
System.out.println(StringUtils.isBlank(null));//true
System.out.println(StringUtils.isBlank(""));//true
System.out.println(StringUtils.isBlank(" "));//true
System.out.println(StringUtils.isBlank(" "));//true
System.out.println(StringUtils.isBlank("abc"));//false
System.out.println(StringUtils.isBlank(" abc "));//false
}
}
ctrl+B溯源查看底层源码
四、StringUtils的其他方法
package com.example.springboottest;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String[] args) {
System.out.println(StringUtils.substring("abc", 1)); // "bc"
System.out.println(StringUtils.leftPad("1", 3, '0')); // "001"
List<String> list = Arrays.asList("a", "b", "c");
System.out.println(StringUtils.join(list, ",")); // "a,b,c"
}
}
可以参考官方的文档
链接: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html