1

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 Answers5

6

Try the followoing :

 if(str.trim().isEmpty()){
         str = null;
 } 
blackSmith
  • 3,054
  • 1
  • 20
  • 37
2

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");
    }
DeiAndrei
  • 947
  • 6
  • 16
1

Suppose your variable is String var

Then,

if(var.replace(" ", "").equals("")) {
    var = null;
}
shyam
  • 1,348
  • 4
  • 19
  • 37
0

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

Rene M.
  • 2,660
  • 15
  • 24
0

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.

Andy Brown
  • 11,766
  • 2
  • 42
  • 61