阅读量:116
在Java中,我们可以使用以下几种方法来检查一个字符串是否不为空:
- 使用String类的isEmpty()方法:isEmpty()方法返回一个布尔值,表示字符串是否为空。如果字符串为空,则返回true,否则返回false。
String str = "Hello";
if(!str.isEmpty()) {
// 字符串不为空
}
- 使用String类的length()方法:length()方法返回字符串的长度,如果长度大于0,则表示字符串不为空。
String str = "World";
if(str.length() > 0) {
// 字符串不为空
}
- 使用StringUtils类(Apache Commons Lang库)的isNotEmpty()方法:StringUtils.isNotEmpty()方法可以帮助我们检查字符串是否不为空。需要先导入Apache Commons Lang库。
String str = "Java";
if(StringUtils.isNotEmpty(str)) {
// 字符串不为空
}
- 使用trim()方法:trim()方法可以去除字符串前后的空格,如果字符串不为空,则去除空格后长度大于0。
String str = " Hello ";
if(str.trim().length() > 0) {
// 字符串不为空
}
这些是一些检查字符串是否不为空的常用方法,根据实际情况选择合适的方法来使用。