How to know if the string variabel contains only space in java?

前端 未结 5 1236
时光取名叫无心
时光取名叫无心 2020-12-22 01:30

I have a variable that\'s a string and I want to replace the string with \"null\" if the variable contains only a space or multiple spaces. How can I do it?

相关标签:
5条回答
  • 2020-12-22 01:58

    First off all you can implement it your self for example by using a regular expression which is very simple.

    The Java Regex definition defines "/s" as the pattern for all whitespace characters. So a String matching "/s+" is empty or only includes whitespaces.

    Here is an example:

    public boolean isEmpty(String value) {
      return value.matches("/s*");
    }
    

    But normaly it isn't a good idea to do this by your self. It is a so common pattern that it is implemented in a lot of libraries already. My best practice in nearly all java apps I've written is to use the apache commons lang library. Which includes the StringUtils class. All methods in this class are nullsave and keep an eye on all possible scenarios about what is for example an empty string.

    So with apache commons it is:

    StringUtils.isBlank(value);
    

    Have a look here: http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/index.html

    0 讨论(0)
  • 2020-12-22 02:05

    Suppose your variable is String var

    Then,

    if(var.replace(" ", "").equals("")) {
        var = null;
    }
    
    0 讨论(0)
  • 2020-12-22 02:15

    How about this?

    if(yourstring.replace(" ","").length()==0) {
        yourstring = null;
    }
    

    Doesn't need regexes so should be a little more efficient than solutions that do.

    0 讨论(0)
  • 2020-12-22 02:21

    Try the followoing :

     if(str.trim().isEmpty()){
             str = null;
     } 
    
    0 讨论(0)
  • 2020-12-22 02:21

    This is a way you could do it:

        String spaces = "   -- - -";
        if (spaces.matches("[ -]*")) {
            System.out.println("Only spaces and/or - or empty");
        }
        else {
            System.out.println("Not only spaces");
        }
    
    0 讨论(0)
提交回复
热议问题