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";
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.
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.
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:
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.
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*$");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With