判断字符串是否为null、是否为空

心已赠人 2022-09-08 15:53 431阅读 0赞

org.apache.commons.lang3.StringUtils (掌握)

Maven依赖

  1. <dependency>
  2. <groupId>org.apache.commons</groupId>
  3. <artifactId>commons-lang3</artifactId>
  4. <version>3.9</version>
  5. </dependency>

示例

  1. import org.apache.commons.lang3.StringUtils;
  2. public class DemoTest {
  3. public static void main(String[] args) {
  4. String str = null;
  5. System.out.println(StringUtils.isBlank(str)); //true
  6. System.out.println(StringUtils.isEmpty(str)); //true
  7. str = "";
  8. System.out.println(StringUtils.isBlank(str)); //true
  9. System.out.println(StringUtils.isEmpty(str)); //true
  10. str = " ";
  11. System.out.println(StringUtils.isBlank(str)); //true
  12. System.out.println(StringUtils.isEmpty(str)); //false
  13. }
  14. }

记忆isBlank()在参数为null、""、" "时,值全部为true,在实际项目中使用到该方法比较多。

isEmpty 和 isBlank 的区别?

  • 英语
    empty
    英 [ˈempti] 美 [ˈempti]
    adj.
    空的;空洞的;空虚的;
    blank
    英 [blæŋk] 美 [blæŋk]
    adj.
    空白的;空的;
  • isEmpty:判断字符串是否为空字符串,只要有任意一个字符(包括空白字符)就不为空。
    其源代码:

    public static boolean isEmpty(CharSequence cs) {

    1. return cs == null || cs.length() == 0;

    }

  • isBlank:判断字符串是否为空字符串,全部空白字符也为空。

  • 源代码

    public static boolean isBlank(CharSequence cs) {

    1. int strLen;
    2. if (cs != null && (strLen = cs.length()) != 0) {
    3. for(int i = 0; i < strLen; ++i) {
    4. // 只要有一个字符不为空白字符就返回 false
    5. if (!Character.isWhitespace(cs.charAt(i))) {
    6. return false;
    7. }
    8. }
    9. return true;
    10. } else {
    11. return true;
    12. }

    }

使用技巧

我们要判断一个字符串为空,绝大部分情况下 “空白字符” 也要为空的,严谨来说肯定要用 isBlank

org.junit.platform.commons.util.StringUtils (了解)

  • 依赖


    org.junit.jupiter
    junit-jupiter
    5.7.2
    test
  • 测试代码

    import org.junit.platform.commons.util.StringUtils;
    public class DemoTest {

    1. public static void main(String[] args) {
    2. String str = null;
    3. System.out.println(StringUtils.isBlank(str)); //true
    4. str = "";
    5. System.out.println(StringUtils.isBlank(str)); //true
    6. str = " ";
    7. System.out.println(StringUtils.isBlank(str)); //true
    8. }

    }

  • 源代码

    public static boolean isBlank(String str) {

    1. return (str == null || str.trim().isEmpty());
    2. }

发表评论

表情:
评论列表 (有 0 条评论,431人围观)

还没有评论,来说两句吧...

相关阅读