Check If a String Has White Space

How do I check that a Java String is not all whitespaces?

Shortest solution I can think of:

if (string.trim().length() > 0) ...

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:

if (string.matches(".*\\w.*")) ...

...which checks for at least one (ASCII) alphanumeric character.

Check if a string has only white spaces in it

You could use trimws, which removes leading/trailing white-space from a character string:

trimws(str) == ""
#[1] TRUE

Check if string has a space

let url = " pic.png"
let whiteSpace = " "
if let hasWhiteSpace = url.rangeOfString(whiteSpace) {
print ("has whitespace")
} else {
print("no whitespace")

Related Topics

Leave a reply