How to Check if a String Contains Whitespace in Rust

Created
Modified

Using char::is_whitespace

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

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

fn main() {
  println!("{}", "Hello World".contains(char::is_whitespace));
  // a non-breaking space
  println!("{}", "Hello\u{A0}World".contains(char::is_whitespace));
  println!("{}", "Hello\taWorld".contains(char::is_whitespace));
}
true
true
true

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).

Using as_bytes Method

If you're only looking for ASCII whitespace:

fn main() {
  let mut s = "Hello World";
  println!("{}", s.as_bytes().iter().any(u8::is_ascii_whitespace));

  // a non-breaking space
  s = "Hello\u{A0}World";
  println!("{}", s.as_bytes().iter().any(u8::is_ascii_whitespace));

  s = "Hello\tWorld";
  println!("{}", s.as_bytes().iter().any(u8::is_ascii_whitespace));
}
true
false
true

Related Tags