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

前端 未结 5 1240
时光取名叫无心
时光取名叫无心 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

提交回复
热议问题