Java中的字符串isNullOrEmpty?

rip*_*234 130 java string

这肯定是之前被问过,但谷歌搜索没有找到它.在任何标准的java库(包括apache/google/...)中,有静态isNullOrEmpty()方法Strings吗?

Boz*_*zho 150

来自Apache commons-lang.

empty和之间的区别blank是:仅由空格组成的字符串是blank但不是empty.

如果可能的话,我通常更喜欢使用apache-commons,而不是编写我自己的实用程序方法,尽管这对于像这样的简单方法也是合理的.

  • 我对空白和空白之间的区别感到困惑,所以我查了一下; 空白表示",",null和任何数量的空格; 空只是""和null. (21认同)

Noa*_*oah 97

如果你正在进行android开发,你可以使用:

TextUtils.isEmpty (CharSequence str) 
Run Code Online (Sandbox Code Playgroud)

在API级别1中添加如果字符串为null或0-length,则返回true.

  • 真是太棒了!这正是我一直在寻找的,不必使用try catch子句,非常感谢! (2认同)

Jar*_*zki 43

com.google.common.base.Strings.isNullOrEmpty(String string)来自Google Guava


Jon*_*eet 26

不,这就是为什么这么多其他图书馆有自己的副本:)


Pet*_*rey 14

你可以添加一个

public static boolean isNullOrBlank(String param) { 
    return param == null || param.trim().length() == 0;
}
Run Code Online (Sandbox Code Playgroud)

我有

public static boolean isSet(String param) { 
    // doesn't ignore spaces, but does save an object creation.
    return param != null && param.length() != 0; 
}
Run Code Online (Sandbox Code Playgroud)


小智 8

检查字符串是否有任何字符,即.not null或whitespaces,check StringUtils.hasText-method(如果你当然使用Spring)

例:

StringUtils.hasText(null) == false
StringUtils.hasText("") == false
StringUtils.hasText(" ") == false
StringUtils.hasText("12345") == true
StringUtils.hasText(" 12345 ") == true
Run Code Online (Sandbox Code Playgroud)