栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

关于StringUtils里isEmpty方法和isBlank方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于StringUtils里isEmpty方法和isBlank方法

一、前言

StringUtils 的操作对象是 Java.lang.String 类型的对象,是 JDK 提供的 String 类型操作方法的补充,输入的 String参数 为 null 也不会抛出 NullPointerException异常 ,而是做了相应处理,例如,如果输入为 null 则返回也是 null 等,具体可以查看源代码,

在实际工作中,我们需要对字符串进行一些校验,比如:是否为 null,是否为空,是否去掉空格、换行符、制表符等。一般都是通过一些框架的工具类去做这些判断,比如:apache 的 commons jar 包,如下。

package org.apache.commons.lang3;

下面主要介绍isEmpty方法和isBlank方法。

二、isEmpty方法
public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

以上是isEmpty方法源代码,由源码可知判断某字符串是否为空的标准是 str==null 或 str.length()==0

举几个例子:

public void test() {
        System.out.println(StringUtils.isEmpty(""));//ture
        System.out.println(StringUtils.isEmpty(" "));//false
        System.out.println(StringUtils.isEmpty("  "));//false
        System.out.println(StringUtils.isEmpty(null));//true
        System.out.println(StringUtils.isEmpty("null"));//false
        System.out.println(StringUtils.isEmpty("  empty  "));//false
    }

三、isBlank方法
public static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs != null && (strLen = cs.length()) != 0) {
            for(int i = 0; i < strLen; ++i) {
                //判断字符是否为空格、制表符、换行符
                if (!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }

以上是isBlank方法的源代码,其中Character.isWhitespace() 方法用于判断指定字符是否为空白字符,空白符包含:空格、tab键、换行符。由源码可知其判断某字符串是否为空或长度为0或由空白符(whitespace) 构成。

举例:

public void test() {
        System.out.println(StringUtils.isBlank(""));//ture
        System.out.println(StringUtils.isBlank(" "));//true
        System.out.println(StringUtils.isBlank("  "));//true
        System.out.println(StringUtils.isBlank(null));//true
        System.out.println(StringUtils.isBlank("null"));//false
        System.out.println(StringUtils.isBlank("  blank  "));//false
        //制表符
        System.out.println(StringUtils.isBlank("t"));//true
        //换行符
        System.out.println(StringUtils.isBlank("n"));//true
        //换页符
        System.out.println(StringUtils.isBlank("f"));//true
        //回车符
        System.out.println(StringUtils.isBlank("r"));//true
    }

四、结论
  1. isEmpty()方法没有忽略空格,是以是否为空和是否存在为判断依据;
  2. isBlank()方法的判断范围更大,它是在isEmpty()方法的基础上增加了字符串为空格、制表符等判断。在实际开发中,isBlank()方法更加常用。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/857961.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号