如何检查字符串是否为非空?
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 */
}
/* ... */
}
当前回答
使用Java 8可选,你可以做:
public Boolean isStringCorrect(String str) {
return Optional.ofNullable(str)
.map(String::trim)
.map(string -> !str.isEmpty())
.orElse(false);
}
在这个表达式中,您也将处理由空格组成的字符串。
其他回答
考虑下面的例子,我在main方法中添加了4个测试用例。当您遵循上面的注释片段时,将通过三个测试用例。
public class EmptyNullBlankWithNull {
public static boolean nullEmptyBlankWithNull(String passedStr) {
if (passedStr != null && !passedStr.trim().isEmpty() && !passedStr.trim().equals("null")) {
// TODO when string is null , Empty, Blank
return true;
}else{
// TODO when string is null , Empty, Blank
return false;
}
}
public static void main(String[] args) {
String stringNull = null; // test case 1
String stringEmpty = ""; // test case 2
String stringWhiteSpace = " "; // test case 3
String stringWhiteSpaceWithNull = " null"; // test case 4
System.out.println("TestCase result:------ "+nullEmptyBlankWithNull(stringWhiteSpaceWithNull));
}
}
但是测试用例4将返回true(它在null之前有空格),这是错误的:
String stringWhiteSpaceWithNull = " null"; // test case 4
我们必须添加以下条件才能使其正常工作:
!passedStr.trim().equals("null")
使用Apache StringUtils的isNotBlank方法
StringUtils.isNotBlank(str)
只有当str不为空时,它才会返回true。
我知道的几乎每个库都定义了一个名为StringUtils、StringUtil或StringHelper的实用程序类,它们通常包含你正在寻找的方法。
我个人最喜欢的是Apache Commons / Lang,在StringUtils类中,你可以同时得到
StringUtils.isEmpty(字符串)和 StringUtils.isBlank (String)方法
(第一个检查字符串是空的还是空的,第二个检查它是空的,空的还是空白的)
在Spring、Wicket和许多其他库中也有类似的实用程序类。如果不使用外部库,您可能希望在自己的项目中引入一个StringUtils类。
更新:许多年过去了,现在我建议使用Guava的Strings.isNullOrEmpty(string)方法。
根据您的实际需要,我建议您选择Guava或Apache Commons。检查我的示例代码中的不同行为:
import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;
/**
* Created by hu0983 on 2016.01.13..
*/
public class StringNotEmptyTesting {
public static void main(String[] args){
String a = " ";
String b = "";
String c=null;
System.out.println("Apache:");
if(!StringUtils.isNotBlank(a)){
System.out.println(" a is blank");
}
if(!StringUtils.isNotBlank(b)){
System.out.println(" b is blank");
}
if(!StringUtils.isNotBlank(c)){
System.out.println(" c is blank");
}
System.out.println("Google:");
if(Strings.isNullOrEmpty(Strings.emptyToNull(a))){
System.out.println(" a is NullOrEmpty");
}
if(Strings.isNullOrEmpty(b)){
System.out.println(" b is NullOrEmpty");
}
if(Strings.isNullOrEmpty(c)){
System.out.println(" c is NullOrEmpty");
}
}
}
结果: Apache: A是空的 B是空白的 C为空白 谷歌: b为NullOrEmpty c为NullOrEmpty
为了完整性:如果您已经在使用Spring框架,则StringUtils提供了该方法
org.springframework.util.StringUtils.hasLength(String str)
返回: 如果String不是null并且有长度,则为true
以及方法
org.springframework.util.StringUtils.hasText(String str)
返回: 如果String不为空,长度大于0,且不包含空格,则为true