如何检查字符串是否为非空?
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 */
}
/* ... */
}
当前回答
处理字符串中的null更好的方法是,
str!=null && !str.equalsIgnoreCase("null") && !str.isEmpty()
简而言之,
str.length()>0 && !str.equalsIgnoreCase("null")
其他回答
你可以使用StringUtils.isEmpty(),如果字符串是空的或空的,则结果为true。
String str1 = "";
String str2 = null;
if(StringUtils.isEmpty(str)){
System.out.println("str1 is null or empty");
}
if(StringUtils.isEmpty(str2)){
System.out.println("str2 is null or empty");
}
会导致
Str1为空或空
Str2为null或空
使用Java 8可选,你可以做:
public Boolean isStringCorrect(String str) {
return Optional.ofNullable(str)
.map(String::trim)
.map(string -> !str.isEmpty())
.orElse(false);
}
在这个表达式中,您也将处理由空格组成的字符串。
我遇到过一种情况,我必须检查“null”(作为字符串)必须被视为空。空格和实际null必须返回true。 我最终确定了下面的函数…
public boolean isEmpty(String testString) {
return ((null==testString) || "".equals((""+testString).trim()) || "null".equals((""+testString).toLowerCase()));
}
在这里添加Android:
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)) {
...
}
如果你需要验证你的方法参数,你可以使用以下简单的方法
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;
}