写了那么久的代码,傻傻分不清楚这两个的区别,今天记录一下,方便后面再查
先看代码
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.
本文介绍了如何在Java中使用ApacheCommonsLang库的StringUtils类的isNotEmpty和isNotBlank方法来检查字符串是否为空或仅包含空白,重点在于两者对空字符串的不同处理。
1951

被折叠的 条评论
为什么被折叠?



