【问题标题】:Check whether a string is not null and not empty检查字符串是否不为空且不为空
【发布时间】:2011-04-05 15:42:15
【问题描述】:

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

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

【问题讨论】:

  • 您可能应该使用PreparedStatement 等,而不是通过字符串连接原语构造SQL 查询。避免各种注入漏洞,更具可读性等。
  • 您可以创建将检查空值或空对象的类。这将帮助您提高重用能力.. stackoverflow.com/a/16833309/1490962

标签: java string string-comparison


【解决方案1】:

要检查字符串是否不为空,您可以检查它是否为null,但这并不能说明带有空格的字符串。您可以使用str.trim() 修剪所有空格,然后链接.isEmpty() 以确保结果不为空。

    if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }

【讨论】:

    【解决方案2】:

    中有一个新方法: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

    【讨论】:

      【解决方案3】:

      如果您需要验证您的方法参数,您可以使用以下简单方法

      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;
      }
      

      【讨论】:

        【解决方案4】:

        我遇到了一种情况,我必须检查“null”(作为字符串)是否必须被视为空。空格和实际的 null 也必须返回 true。 我终于确定了以下功能...

        public boolean isEmpty(String testString) {
          return ((null==testString) || "".equals((""+testString).trim()) || "null".equals((""+testString).toLowerCase()));
        }
        

        【讨论】:

          【解决方案5】:
          import android.text.TextUtils;
          
          if (!TextUtils.isEmpty(str)||!str.equalsIgnoreCase("") {
              ...
          }
          

          【讨论】:

          • 添加几句解释总比一些代码要好。例如,为什么要导入库?
          【解决方案6】:

          使用Java 8 Optional,您可以:

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

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

          【讨论】:

            【解决方案7】:

            检查对象中的所有字符串属性是否为空(而不是按照java反射api方法在所有字段名称上使用!=null

            private String name1;
            private String name2;
            private String name3;
            
            public boolean isEmpty()  {
            
                for (Field field : this.getClass().getDeclaredFields()) {
                    try {
                        field.setAccessible(true);
                        if (field.get(this) != null) {
                            return false;
                        }
                    } catch (Exception e) {
                        System.out.println("Exception occurred in processing");
                    }
                }
                return true;
            }
            

            如果String字段的所有值都是空的,这个方法会返回true,如果String属性中存在任何一个值,这个方法会返回false

            【讨论】:

              【解决方案8】:

              如果您使用的是 Spring Boot,那么下面的代码将完成这项工作

              StringUtils.hasLength(str)
              

              【讨论】:

                【解决方案9】:

                isEmpty() 呢?

                if(str != null && !str.isEmpty())
                

                请务必按此顺序使用&& 的部分,因为如果&& 的第一部分失败,java 将不会继续评估第二部分,从而确保您不会从@987654325 获得空指针异常@ 如果str 为空。

                请注意,它仅在 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 ) )
                

                【讨论】:

                • 请注意,isEmpty() 似乎需要一个 String 实例(非静态)。在空引用上调用它会抛出 NullPointerException。
                • 或 if(str != null && !str.trim().isEmpty()),忽略空格。
                • if((txt.getText().length()) == 0 ) // 从布局中获取元素
                • 我建议使用TextUtils.isEmpty(String) 来检查字符串是否为空或为空。又好又短。 TextUtils 类是 Android SDK 的一部分。
                • @user1154390:有时为了清楚起见,明确使用 true 和 false 是值得的,但是当条件返回 true 表示 true 并且 false 表示 false 时,它​​不必要的复杂性。简单地说(str != null && str.length() > 0)
                【解决方案10】:

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

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

                总之,

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

                【讨论】:

                  【解决方案11】:

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

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

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

                  【讨论】:

                  • 请注意,StringUtils 的文档明确指出“主要供框架内部使用;考虑使用 Apache 的 Commons Lang 以获得更全面的字符串实用程序套件。”
                  【解决方案12】:

                  根据输入返回真或假

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

                  【讨论】:

                    【解决方案13】:

                    如果您正在使用 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
                    

                    【讨论】:

                    • 这就是我喜欢这样做的方式,当我担心性能成本或副作用,并且没有现成的导入时。
                    【解决方案14】:

                    简单地说,也可以忽略空白:

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

                    【讨论】:

                      【解决方案15】:

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

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

                      【讨论】:

                      • 我建议使用贴图进行修剪,例如: Optional.ofNullable(str) .map(String::trim) .filter(String::isEmpty) .ifPresent(this::setStringMethod);
                      【解决方案16】:

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

                      我个人最喜欢的是Apache Commons / Lang,在StringUtils 类中,你会得到两个

                      1. StringUtils.isEmpty(String)
                      2. StringUtils.isBlank(String)方法

                      (第一个检查字符串是否为空或空,第二个检查它是否为空、空或仅空格)

                      在 Spring、Wicket 和许多其他库中有类似的实用程序类。如果你不使用外部库,你可能想在你自己的项目中引入一个 StringUtils 类。


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

                      【讨论】:

                      • 我想问你为什么现在推荐这个?我想知道 Strings.isNullOrEmpty(string) 和 StringUtils.isEmpty(String) 之间是否有区别
                      • @vicangel Apache Commons 方法充满了假设和我没有要求的东西。有了番石榴,我得到的正是我所要求的,不多也不少
                      【解决方案17】:

                      为了完整性:如果您已经在使用 Spring 框架StringUtils 提供了方法

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

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

                      还有方法

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

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

                      【讨论】:

                      • 我们可以使用 StringUtils.isEmpty(param) 方法。
                      【解决方案18】:

                      简单的解决方案:

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

                      【讨论】:

                        【解决方案19】:

                        我会根据您的实际需要建议 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

                        【讨论】:

                          【解决方案20】:

                          使用org.apache.commons.lang.StringUtils

                          我喜欢将 Apache commons-lang 用于此类事情,尤其是 StringUtils 实用程序类:

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

                          【讨论】:

                          • 如果你可以只使用 isEmpty,Apache commons-lang 不是矫枉过正吗?只是好奇。
                          • @zengr - 不,因为你肯定也会使用其他东西 :)
                          • @zengr 确实,如果你只使用isEmptyisBlank,那么包含第三方库可能没什么用。您可以简单地创建自己的实用程序类来提供这样的方法。然而,正如 Bozho 所解释的,commons-lang 项目提供了许多有用的方法!
                          • 因为StringUtils.isNotBlank(str) 也会进行空值检查。
                          • 如果您使用 Spring Framework,这可能已经捆绑在框架的 jar 中。
                          【解决方案21】:

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

                          isNotBlank() 检查输入参数是否为:

                          • 不为空,
                          • 不是空字符串 ("")
                          • 不是一系列空白字符 (" ")

                          isNotEmpty() 只检查输入参数是

                          • 不为空
                          • 不是空字符串 ("")

                          【讨论】:

                            【解决方案22】:

                            使用 Apache StringUtils 的 isNotBlank 方法,如

                            StringUtils.isNotBlank(str)
                            

                            只有当str不为null且不为空时才会返回true。

                            【讨论】:

                            • 其实这里str为null,语句返回true
                            • 那是真的,我的错!而是使用 apache-commons 的 StringUtils.isNotEmpty(str) 来完成这项工作。
                            【解决方案23】:

                            我已经创建了自己的实用程序函数来一次检查多个字符串,而不是使用充满if(str != null &amp;&amp; !str.isEmpty &amp;&amp; str2 != null &amp;&amp; !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
                            }
                            

                            【讨论】:

                            • 使用签名会更好:areSet(String... strings) 然后可以在不创建数组的情况下调用:if(!StringUtils.areSet(firstName, lastName, address))
                            【解决方案24】:

                            您可以使用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 或为空

                            【讨论】:

                            • 或者直接使用isNotBlank
                            【解决方案25】:

                            这对我有用:

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

                            如果给定字符串为 null 或为空字符串,则返回 true。

                            考虑使用 nullToEmpty 规范化您的字符串引用。如果你 做,你可以使用 String.isEmpty() 代替这个方法,你不会 需要特殊的 null 安全形式的方法,例如 String.toUpperCase 任何一个。或者,如果您想“在另一个方向”标准化 将空字符串转换为null,可以使用emptyToNull。

                            【讨论】:

                            • com.google.guavaguava12.0
                            【解决方案26】:

                            test 等于一个空字符串并且在同一个条件下为 null:

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

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

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

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

                            【讨论】:

                            • 那么为什么要添加从未达到的代码str != null!"".equals(str) 已经做好了
                            【解决方案27】:

                            如果您不想包含整个库;只需包含您想要的代码。您必须自己维护它;但这是一个非常简单的功能。这里复制自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;
                            }
                            

                            【讨论】:

                              【解决方案28】:

                              只需在此处添加 Android:

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

                              【讨论】:

                              • @staticx,StringUtils 方法在 Lang 2.0 版中已更改。它不再修剪 CharSequence。该功能在 isBlank() 中可用。
                              【解决方案29】:

                              添加到@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 的代码是可疑的并且可能存在错误,因为它可能无法处理所有不允许 @987654327 的情况@ 是有道理的(尽管对于 SQL,我可以理解为 SQL/HQL 对 '' 很奇怪)。

                              【讨论】:

                              • 第二个番石榴也是。 Guava 遵循多个静态类的约定。对于 String,尝试使用 Strings 的静态方法,例如 isNullOrEmpty(str)。
                              【解决方案30】:

                              正如 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 **/
                              }
                              

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

                              【讨论】:

                              猜你喜欢
                              • 2019-01-25
                              • 2020-05-29
                              • 2015-06-12
                              • 2015-06-05
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              相关资源
                              最近更新 更多