How do I check whether input string contains any spaces?

A simple answer, along similar lines to the previous ones is:

str.matches(".*\\s.*")
  • The first ".*" says that there can be zero or more instances of any character in front of the space.
  • The "\\s" says it must contain any whitespace character.
  • The last ".*" says there can be zero or more instances of any character after the space.

When you put all those together, this returns true if there are one or more whitespace characters anywhere in the string.

Here is a simple test you can run to benchmark your solution against:

boolean containsWhitespace(String str){
    return str.matches(".*\\s.*");
}

String[] testStrings = {"test", " test", "te st", "test ", "te   st", 
                        " t e s t ", " ", "", "\ttest"};
for (String eachString : testStrings) {
        System.out.println( "Does \"" + eachString + "\" contain whitespace? " + 
                             containsWhitespace(eachString));
}

Why use a regex?

name.contains(" ")

That should work just as well, and be faster.


If you will use Regex, it already has a predefined character class "\S" for any non-whitespace character.

!str.matches("\\S+")

tells you if this is a string of at least one character where all characters are non-whitespace

Tags:

Java

Regex