如何检查字符串是否为非空?
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-11中有一个新方法:String#isBlank
如果字符串为空或只包含空白代码点则返回true,否则返回false。
jshell> "".isBlank()
$7 ==> true
jshell> " ".isBlank()
$8 ==> true
jshell> " ! ".isBlank()
$9 ==> false
这可以与Optional结合起来检查字符串是否为null或空
boolean isNullOrEmpty = Optional.ofNullable(str).map(String::isBlank).orElse(true);
字符串#是空白
其他回答
使用org.apache.commons.lang.StringUtils
我喜欢用Apache common -lang来做这些事情,尤其是StringUtils实用程序类:
import org.apache.commons.lang.StringUtils;
if (StringUtils.isNotBlank(str)) {
...
}
if (StringUtils.isBlank(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;
}
考虑下面的例子,我在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")
简单地说,忽略空白:
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不会进行第二次检查)!
重要:不要用==表示字符串相等。==检查指针是否相等,而不是值。两个字符串可以在不同的内存地址(两个实例),但具有相同的值!