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

荒凉一梦 提交于 2019-11-28 11:29:37

问题


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



来源:https://stackoverflow.com/questions/26017364/how-to-know-if-the-string-variabel-contains-only-space-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!