如何检查字符串是否为非空?
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 */
}
/* ... */
}
当前回答
为了完整性:如果您已经在使用Spring框架,则StringUtils提供了该方法
org.springframework.util.StringUtils.hasLength(String str)
返回: 如果String不是null并且有长度,则为true
以及方法
org.springframework.util.StringUtils.hasText(String str)
返回: 如果String不为空,长度大于0,且不包含空格,则为true
其他回答
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)||!str.equalsIgnoreCase("") {
...
}
如何:
if(str!= null && str.length() != 0 )
要检查字符串是否为空,可以检查它是否为空,但这不能说明有空格的字符串。您可以使用str.trim()来修剪所有空白,然后链接. isempty()以确保结果不为空。
if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
使用org.apache.commons.lang.StringUtils
我喜欢用Apache common -lang来做这些事情,尤其是StringUtils实用程序类:
import org.apache.commons.lang.StringUtils;
if (StringUtils.isNotBlank(str)) {
...
}
if (StringUtils.isBlank(str)) {
...
}
简单地说,忽略空白:
if (str == null || str.trim().length() == 0) {
// str is empty
} else {
// str is not empty
}