Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains whitespace?

Tags:

string

rust

How do I check if a string contains any whitespace in Rust?

For example, these should all return true:

  • "Hello, world!"
  • "Hello\n"
  • "This\tis\ta\ttab"
like image 294
Camelid Avatar asked Oct 14 '20 20:10

Camelid


People also ask

How do you check if a string contains a space in C++?

The isspace() function in C++ checks if the given character is a whitespace character or not.

How do you check if a string contains a space in Python?

Python String isspace() is a built-in method used for string handling. The isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters such as: ' ' – Space.


2 Answers

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));
like image 189
Camelid Avatar answered Nov 04 '22 03:11

Camelid


As someone mentioned, if you do not need to deal with Unicode, it will be faster to just explicitly name the characters you care about:

fn main() {
   let a = vec!["false", "true space", "true newline\n", "true\ttab"];
   let a2: &[char] = &[' ', '\n', '\t'];

   for s in a.iter() {
      let b = s.contains(a2);
      println!("{}", b);
   }
}
like image 32
Zombo Avatar answered Nov 04 '22 01:11

Zombo