- 使用
isEmpty()方法判断字符串是否为空,例如:
String str = "";
if(str.isEmpty()) {
System.out.println("字符串为空");
}
- 使用
StringUtils工具类中的isBlank()方法判断字符串是否为空或只包含空白字符,例如:
import org.apache.commons.lang3.StringUtils;
String str = " ";
if(StringUtils.isBlank(str)) {
System.out.println("字符串为空或只包含空白字符");
}
- 使用
trim()方法去除字符串两端的空白字符,然后再判断是否为空,例如:
String str = " ";
if(str.trim().isEmpty()) {
System.out.println("字符串为空");
}
- 使用正则表达式去除字符串中的空白字符,然后再判断是否为空,例如:
String str = " ";
str = str.replaceAll("\\s", "");
if(str.isEmpty()) {
System.out.println("字符串为空");
}
- 使用
Objects工具类中的isNull()方法判断字符串是否为null,例如:
import java.util.Objects;
String str = null;
if(Objects.isNull(str)) {
System.out.println("字符串为空");
}