Check whether a string is not null and not empty

后端 未结 30 2438
予麋鹿
予麋鹿 2020-11-22 02:13

How can I check whether a string is not null and not empty?

public void doStuff(String str)
{
    if (str != null && str != \"**here I want to check          


        
30条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 03:12

    I would advise Guava or Apache Commons according to your actual need. Check the different behaviors in my example code:

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

    Result:
    Apache:
    a is blank
    b is blank
    c is blank
    Google:
    b is NullOrEmpty
    c is NullOrEmpty

提交回复
热议问题