如何检查字符串是否为非空?
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 */
}
/* ... */
}
当前回答
我知道的几乎每个库都定义了一个名为StringUtils、StringUtil或StringHelper的实用程序类,它们通常包含你正在寻找的方法。
我个人最喜欢的是Apache Commons / Lang,在StringUtils类中,你可以同时得到
StringUtils.isEmpty(字符串)和 StringUtils.isBlank (String)方法
(第一个检查字符串是空的还是空的,第二个检查它是空的,空的还是空白的)
在Spring、Wicket和许多其他库中也有类似的实用程序类。如果不使用外部库,您可能希望在自己的项目中引入一个StringUtils类。
更新:许多年过去了,现在我建议使用Guava的Strings.isNullOrEmpty(string)方法。
其他回答
那么isEmpty()呢?
if(str != null && !str.isEmpty())
请确保按此顺序使用&&的部分,因为如果&&的第一部分失败,java将不会继续计算第二部分,从而确保如果str为空,则不会从str. isempty()获得空指针异常。
注意,它只在Java SE 1.6以后可用。你必须在以前的版本上检查str.length() == 0。
也可以忽略空白:
if(str != null && !str.trim().isEmpty())
(从Java 11开始,str.trim().isEmpty()可以简化为str.isBlank(),这也将测试其他Unicode空白)
封装在一个方便的函数中:
public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}
就变成:
if( !empty( str ) )
如果你不想包含整个库;只包括你想要的代码。你得自己维护;但这是一个很简单的函数。这里是从commons.apache.org复制的
/**
* <p>Checks if a String is whitespace, empty ("") or null.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is null, empty or whitespace
* @since 2.0
*/
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
加上@BJorn和@SeanPatrickFloyd的番石榴方法是:
Strings.nullToEmpty(str).isEmpty();
// or
Strings.isNullOrEmpty(str);
Commons Lang有时更具可读性,但我已经慢慢地更多地依赖于Guava,有时Commons Lang在涉及到isBlank()时令人困惑(如什么是空白或不是空白)。
Guava版本的Commons Lang isBlank将是:
Strings.nullToEmpty(str).trim().isEmpty()
我会说,代码不允许“”(空)和null是可疑的,潜在的bug,因为它可能无法处理所有不允许null有意义的情况(尽管对于SQL,我可以理解为SQL/HQL是奇怪的”)。
使用org.apache.commons.lang.StringUtils
我喜欢用Apache common -lang来做这些事情,尤其是StringUtils实用程序类:
import org.apache.commons.lang.StringUtils;
if (StringUtils.isNotBlank(str)) {
...
}
if (StringUtils.isBlank(str)) {
...
}
str != null && str.length() != 0
另外
str != null && !str.equals("")
or
str != null && !"".equals(str)
注意:第二次检查(第一个和第二个替代)假设str不为空。这只是因为第一次检查是这样做的(如果第一次检查为假,Java不会进行第二次检查)!
重要:不要用==表示字符串相等。==检查指针是否相等,而不是值。两个字符串可以在不同的内存地址(两个实例),但具有相同的值!