如何检查字符串是否为非空?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}
如何检查字符串是否为非空?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}
当前回答
简单地说,忽略空白:
if (str == null || str.trim().length() == 0) {
// str is empty
} else {
// str is not empty
}
其他回答
str != null && str.length() != 0
另外
str != null && !str.equals("")
or
str != null && !"".equals(str)
注意:第二次检查(第一个和第二个替代)假设str不为空。这只是因为第一次检查是这样做的(如果第一次检查为假,Java不会进行第二次检查)!
重要:不要用==表示字符串相等。==检查指针是否相等,而不是值。两个字符串可以在不同的内存地址(两个实例),但具有相同的值!
如果你需要验证你的方法参数,你可以使用以下简单的方法
public class StringUtils {
static boolean anyEmptyString(String ... strings) {
return Stream.of(strings).anyMatch(s -> s == null || s.isEmpty());
}
}
例子:
public String concatenate(String firstName, String lastName) {
if(StringUtils.anyBlankString(firstName, lastName)) {
throw new IllegalArgumentException("Empty field found");
}
return firstName + " " + lastName;
}
要检查字符串是否为空,可以检查它是否为空,但这不能说明有空格的字符串。您可以使用str.trim()来修剪所有空白,然后链接. isempty()以确保结果不为空。
if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
测试等于一个空字符串和null在相同的条件:
if(!"".equals(str) && str != null) {
// do stuff.
}
如果str为空则不抛出NullPointerException,因为Object.equals()如果arg为空则返回false。
另一个构造str.equals("")会抛出可怕的NullPointerException。有些人可能认为在调用equals()时使用String字面值作为对象是一种糟糕的形式,但它确实完成了这项工作。
还有这个答案:https://stackoverflow.com/a/531825/1532705
如何:
if(str!= null && str.length() != 0 )