首页 文章

检查字符串是否为空且不为空

提问于
浏览
420

如何检查字符串是否为空且不为空?

public void doStuff(String str)
{
    if (str != null && str != "**here I want to check the 'str' is empty or not**")
    {
        /* handle empty string */
    }
    /* ... */
}

26 回答

  • 3

    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 ) )
    
  • 820

    使用org.apache.commons.lang.StringUtils

    我喜欢使用Apache commons-lang来做这些事情,尤其是StringUtils实用程序类:

    import org.apache.commons.lang.StringUtils;
    
    if (StringUtils.isNotBlank(str)) {
        ...
    } 
    
    if (StringUtils.isBlank(str)) {
        ...
    }
    
  • 24

    只需在此处添加Android:

    import android.text.TextUtils;
    
    if (!TextUtils.isEmpty(str)) {
    ...
    }
    
  • 4

    添加到@BJorn和@SeanPatrickFloyd Guava的方法是:

    Strings.nullToEmpty(str).isEmpty(); 
    // or
    Strings.isNullOrEmpty(str);
    

    Commons Lang有时候更具可读性,但我一直在慢慢依赖 Guava 加上有时候Commons Lang在 isBlank() 时会感到困惑(就像在什么是空白时一样) .

    Guava 版的Commons Lang isBlank 将是:

    Strings.nullToEmpty(str).trim().isEmpty()
    

    我会说不允许 "" (空) AND null 的代码是可疑的并且可能是错误的,因为它可能无法处理所有不允许 null 有意义的情况(尽管对于SQL我可以理解为SQL / HQL很奇怪关于 '' ) .

  • 1
    str != null && str.length() != 0
    

    或者

    str != null && !str.equals("")
    

    要么

    str != null && !"".equals(str)
    

    注意:第二个检查(第一个和第二个备选方案)假定str不为空 . 这只是因为第一次检查是这样做的(如果第一次检查是假的,那么Java不会进行第二次检查)!

    重要提示:请勿使用==进行字符串相等 . ==检查指针是否相等,而不是值 . 两个字符串可以位于不同的内存地址(两个实例)中,但具有相同的值!

  • 5

    这对我有用:

    import com.google.common.base.Strings;
    
    if (!Strings.isNullOrEmpty(myString)) {
           return myString;
    }
    

    如果给定字符串为null或为空字符串,则返回true . 考虑使用nullToEmpty规范化字符串引用 . 如果这样做,您可以使用String.isEmpty()而不是此方法,并且您也不需要特殊的空类安全形式的方法,如String.toUpperCase . 或者,如果您想要“向另一个方向”规范化,将空字符串转换为null,则可以使用emptyToNull .

  • 5

    我所知道的几乎每个库都定义了一个名为 StringUtilsStringUtilStringHelper 的实用程序类,它们通常包含您要查找的方法 .

    我个人最喜欢的是Apache Commons / Lang,在StringUtils类中,你可以得到它们
    StringUtils.isEmpty(String)和StringUtils.isBlank(String)方法(第一个检查字符串是空还是空,第二个检查它是否为空,仅为空或空白)
    Spring,Wicket和许多其他库中都有类似的实用程序类 . 如果不使用外部库,则可能需要在自己的项目中引入StringUtils类 .


    更新:多年过去了,这些天我建议使用GuavaStrings.isNullOrEmpty(string)方法 .

  • 3

    怎么样:

    if(str!= null && str.length() != 0 )
    
  • 11

    使用Apache StringUtils的isNotBlank方法

    StringUtils.isNotBlank(str)
    

    仅当str不为null且不为空时,它才会返回true .

  • 1

    如果你不愿意自己维护它;但这是一个非常直接的功能 . 在这里复制自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;
    }
    
  • 0

    你应该使用 org.apache.commons.lang3.StringUtils.isNotBlank()org.apache.commons.lang3.StringUtils.isNotEmpty . 这两者之间的决定是基于您实际想要检查的内容 .

    isNotBlank()检查输入参数是:

    • 不是空的,

    • 不是空字符串(“”)

    • 不是空格字符序列(" ")

    isNotEmpty()仅检查输入参数是否为

    • 不为空

    • 不是空字符串(“”)

  • 42

    这有点太晚了,但这是一种功能性的检查方式:

    Optional.ofNullable(str)
        .filter(s -> !(s.trim().isEmpty()))
        .ifPresent(result -> {
           // your query setup goes here
        });
    
  • 190

    根据输入返回true或false

    Predicate<String> p = (s)-> ( s != null && !s.isEmpty());
    p.test(string);
    
  • 2

    java-11中有一种新方法: String#isBlank

    如果字符串为空或仅包含空格代码点,则返回true,否则返回false .

    jshell> "".isBlank()
    $7 ==> true
    
    jshell> " ".isBlank()
    $8 ==> true
    
    jshell> " ! ".isBlank()
    $9 ==> false
    

    这可以与 Optional 结合使用,以检查字符串是否为空或空

    boolean isNullOrEmpty = Optional.ofNullable(str).map(String::isBlank).orElse(true);
    

    String#isBlank

  • 0

    test等于空字符串,并且在相同的条件中为null:

    if(!"".equals(str) && str != null) {
        // do stuff.
    }
    

    才不是抛出 NullPointerException 如果str为null,因为如果arg是 null ,则Object.equals()返回false .

    另一个构造 str.equals("") 会抛出可怕的 NullPointerException . 有些人可能会考虑使用字符串文字作为调用对象的错误形式,但它可以完成工作 .

    同时检查这个答案:https://stackoverflow.com/a/531825/1532705

  • 1

    简单方案:

    private boolean stringNotEmptyOrNull(String st) {
        return st != null && !st.isEmpty();
    }
    
  • 0

    正如上面所说的seanizer,Apache StringUtils非常棒,如果你要包含 Guava ,你应该做以下事情;

    public List<Employee> findEmployees(String str, int dep) {
     Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");
     /** code here **/
    }
    

    我还建议您按名称而不是索引来引用结果集中的列,这将使您的代码更易于维护 .

  • 103

    我已经创建了自己的实用程序函数来同时检查多个字符串,而不是使用 if(str != null && !str.isEmpty && str2 != null && !str2.isEmpty) 的if语句 . 这是功能:

    public class StringUtils{
    
        public static boolean areSet(String... strings)
        {
            for(String s : strings)
                if(s == null || s.isEmpty)
                    return false;
    
            return true;
        }   
    
    }
    

    所以我可以简单地写:

    if(!StringUtils.areSet(firstName,lastName,address)
    {
        //do something
    }
    
  • 0

    您可以使用StringUtils.isEmpty(),如果字符串为null或为空,则结果为true .

    String str1 = "";
     String str2 = null;
    
     if(StringUtils.isEmpty(str)){
         System.out.println("str1 is null or empty");
     }
    
     if(StringUtils.isEmpty(str2)){
         System.out.println("str2 is null or empty");
     }
    

    会导致

    str1为null或空

    str2为null或空

  • 4

    我会根据你的实际需要建议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");
        }
      }
    }
    

    结果:
    阿帕奇:
    a是空白的
    b是空白的
    c是空白的
    谷歌:
    b是NullOrEmpty
    c是NullOrEmpty

  • 7

    如果您使用的是Java 8并希望采用更多的功能编程方法,则可以定义一个管理控件的 Function ,然后您可以在需要时重复使用它和 apply() .

    来练习,你可以将 Function 定义为

    Function<String, Boolean> isNotEmpty = s -> s != null && !"".equals(s)
    

    然后,您只需将 apply() 方法调用为:

    String emptyString = "";
    isNotEmpty.apply(emptyString); // this will return false
    
    String notEmptyString = "StackOverflow";
    isNotEmpty.apply(notEmptyString); // this will return true
    

    如果您愿意,可以定义 Function ,检查 String 是否为空,然后使用 ! 取消它 .

    在这种情况下, Function 将如下所示:

    Function<String, Boolean> isEmpty = s -> s == null || "".equals(s)
    

    然后,您只需将 apply() 方法调用为:

    String emptyString = "";
    !isEmpty.apply(emptyString); // this will return false
    
    String notEmptyString = "StackOverflow";
    !isEmpty.apply(notEmptyString); // this will return true
    
  • 2

    完整性:如果您是 already using the Spring framework ,则 StringUtils 提供 method

    org.springframework.util.StringUtils.hasLength(String str)
    

    返回:如果String不为null且具有长度,则返回true

    as well as the method

    org.springframework.util.StringUtils.hasText(String str)
    

    返回:如果String不为null,其长度大于0,并且它不包含空格,则返回true

  • 5

    简单地说,也要忽略空格:

    if (str == null || str.trim().length() == 0) {
        // str is empty
    } else {
        // str is not empty
    }
    
  • 0

    如果您使用Spring框架,那么您可以使用方法:

    org.springframework.util.StringUtils.isEmpty(@Nullable Object str);
    

    此方法接受任何Object作为参数,将其与null和空String进行比较 . 因此,对于非null非String对象,此方法永远不会返回true .

  • 23

    使用Java 8 Optional,您可以:

    public Boolean isStringCorrect(String str) {
            return Optional.ofNullable(str)
                    .map(String::trim)
                    .map(string -> !str.isEmpty())
                    .orElse(false);
        }
    

    在此表达式中,您还将处理由空格组成的 String .

  • 32

    在字符串中处理null的更好方法是,

    str!=null && !str.equalsIgnoreCase("null") && !str.isEmpty()
    

    简而言之,

    str.length()>0 && !str.equalsIgnoreCase("null")
    

相关问题