How to check if a string contains whitespace?

You can pass char::is_whitespace to .contains():

assert!("Hello, world!".contains(char::is_whitespace));
assert!("Hello\n".contains(char::is_whitespace));
assert!("This\tis\ta\ttab".contains(char::is_whitespace));

char::is_whitespace returns true if the character has the Unicode White_Space property.

Alternatively, you can use char::is_ascii_whitespace if you only want to match ASCII whitespace (space, horizontal tab, newline, form feed, or carriage return):

// This has a non-breaking space, which is not ASCII.
let string = "Hello,\u{A0}Rust!\n";

// Thus, it's *not* ASCII whitespace
assert!(!string.contains(char::is_ascii_whitespace));
// but it *is* Unicode whitespace.
assert!(string.contains(char::is_whitespace));

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)