I want to check that Java String or character array is not just made up of whitespaces, using Java?
This is a very similar question except it's Javascript:
How can I check if string contains characters & whitespace, not just whitespace?
EDIT: I removed the bit about alphanumeric characters, so it makes more sense.
will check : - is it null - is it only space - is it empty string ""
https://www.programcreek.com/java-api-examples/?class=com.mysql.jdbc.StringUtils&method=isEmptyOrWhitespaceOnly
trim() and other mentioned regular expression do not work for all types of whitespaces
i.e: Unicode Character 'LINE SEPARATOR' http://www.fileformat.info/info/unicode/char/2028/index.htm
Java functions Character.isWhitespace() covers all situations.
That is why already mentioned solution StringUtils.isWhitespace( String ) /or StringUtils.isBlank(String) should be used.
Slightly shorter than what was mentioned by Carl Smotricz:
Shortest solution I can think of:
This only checks for (non) white space. If you want to check for particular character classes, you need to use the mighty
match()
with a regexp such as:...which checks for at least one (ASCII) alphanumeric character.
The trim method should work great for you.
http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/lang/String.html#trim()
You could trim and then compare to an empty string or possibly check the length for 0.
This answer focusses more on the sidenote "i.e. has at least one alphanumeric character". Besides that, it doesn't add too much to the other (earlier) solution, except that it doesn't hurt you with NPE in case the String is
null
.We want
false
if (1) s isnull
or (2) s is empty or (3) s only contains whitechars.