StringUtils.isNotEmpty()和StringUtils.isNotBlank()的区别

本文介绍了如何在Java中使用ApacheCommonsLang库的StringUtils类的isNotEmpty和isNotBlank方法来检查字符串是否为空或仅包含空白,重点在于两者对空字符串的不同处理。

写了那么久的代码,傻傻分不清楚这两个的区别,今天记录一下,方便后面再查

先看代码

package com.example.test.string;

import org.apache.commons.lang3.StringUtils;

public class StringValidator {
    public static void main(String[] args) {
        // 示例字符串
        String emptyString = "";
        String whitespaceString = "   ";
        String validString = "Hello, World!";
        String nullString = null;

        // 使用 StringUtils.isNotEmpty() 检查字符串是否非空
        if (StringUtils.isNotEmpty(emptyString)) {
            System.out.println("The string is not empty.");
        } else {
            System.out.println("The string is empty.");
        }

        if (StringUtils.isNotEmpty(whitespaceString)) {
            System.out.println("The string is not empty.");
        } else {
            System.out.println("The string is empty.");
        }

        if (StringUtils.isNotEmpty(validString)) {
            System.out.println("The string is not empty.");
        } else {
            System.out.println("The string is empty.");
        }

        if (StringUtils.isNotEmpty(nullString)) {
            System.out.println("The string is not empty.");
        } else {
            System.out.println("The string is empty.");
        }

        // 使用 StringUtils.isNotBlank() 检查字符串是否非空白
        if (StringUtils.isNotBlank(emptyString)) {
            System.out.println("The string is not blank.");
        } else {
            System.out.println("The string is blank.");
        }

        if (StringUtils.isNotBlank(whitespaceString)) {
            System.out.println("The string is not blank.");
        } else {
            System.out.println("The string is blank.");
        }

        if (StringUtils.isNotBlank(validString)) {
            System.out.println("The string is not blank.");
        } else {
            System.out.println("The string is blank.");
        }

        if (StringUtils.isNotBlank(nullString)) {
            System.out.println("The string is not blank.");
        } else {
            System.out.println("The string is blank.");
        }
    }
}

总结:主要区别在对" "处理,其他都是一样的,

isNotBlank判断" "为false,
isNotEmpty判断" "为true.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值