How to know if the string variabel contains only s

2019-02-28 04:13发布

问题:

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?

回答1:

Try the followoing :

 if(str.trim().isEmpty()){
         str = null;
 } 


回答2:

Suppose your variable is String var

Then,

if(var.replace(" ", "").equals("")) {
    var = null;
}


回答3:

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


回答4:

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.



回答5:

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