Best way to verify string is empty or null

前端 未结 13 839
野的像风
野的像风 2020-12-14 15:30

i am sure this must have been asked before in different ways - as isEmptyOrNull is so common yet people implement it differently. but i have below curious query in terms of

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 15:55

    To detect if a string is null or empty, you can use the following without including any external dependencies on your project and still keeping your code simple/clean:

    if(myString==null || myString.isEmpty()){
        //do something
    }
    

    or if blank spaces need to be detected as well:

    if(myString==null || myString.trim().isEmpty()){
        //do something
    }
    

    you could easily wrap these into utility methods to be more concise since these are very common checks to make:

    public final class StringUtils{
    
        private StringUtils() { }   
    
        public static bool isNullOrEmpty(string s){
            if(s==null || s.isEmpty()){
                return true;
            }
            return false;
        }
    
        public static bool isNullOrWhiteSpace(string s){
            if(s==null || s.trim().isEmpty()){
                return true;
            }
            return false;
        }
    }
    

    and then call these methods via:

    if(StringUtils.isNullOrEmpty(myString)){...}

    and

    if(StringUtils.isNullOrWhiteSpace(myString)){...}

提交回复
热议问题