Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find whitespace in a String?

Tags:

java

string

space

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";

like image 712
jimmy Avatar asked Nov 01 '10 09:11

jimmy


People also ask

How do you check for whitespace in a string?

Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.

How do you check if a character is a whitespace?

IsWhiteSpace(String, Int32) Method. This method is used to check whether a character in the specified string at the specified position can be categorized as whitespace or not. It returns True when the character is a whitespace character otherwise it returns False.


2 Answers

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.

like image 28
Sean Patrick Floyd Avatar answered Sep 21 '22 01:09

Sean Patrick Floyd


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*$"); 
like image 105
Mark Byers Avatar answered Sep 21 '22 01:09

Mark Byers