How can I find whitespace in a String?

How can I check to see if a String contains a whitespace character, an empty space or " ". If possible, please provide a Java example.

For example: String = "test word";


Solution 1:

For checking if a string contains whitespace use a Matcher and call its find method.

Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();

If you want to check if it only consists of whitespace then you can use String.matches:

boolean isWhitespace = s.matches("^\\s*$");

Solution 2:

Check whether a String contains at least one white space character:

public static boolean containsWhiteSpace(final String testCode){
    if(testCode != null){
        for(int i = 0; i < testCode.length(); i++){
            if(Character.isWhitespace(testCode.charAt(i))){
                return true;
            }
        }
    }
    return false;
}

Reference:

  • Character.isWhitespace(char)

Using the Guava library, it's much simpler:

return CharMatcher.WHITESPACE.matchesAnyOf(testCode);

CharMatcher.WHITESPACE is also a lot more thorough when it comes to Unicode support.

Solution 3:

This will tell if you there is any whitespaces:

Either by looping:

for (char c : s.toCharArray()) {
    if (Character.isWhitespace(c)) {
       return true;
    }
}

or

s.matches(".*\\s+.*")

And StringUtils.isBlank(s) will tell you if there are only whitepsaces.

Solution 4:

Use Apache Commons StringUtils:

StringUtils.containsWhitespace(str)