Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
754 views
in Technique[技术] by (71.8m points)

rust - How to check if a string contains whitespace?

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

For example, these should all return true:

  • "Hello, world!"
  • "Hello "
  • "Thisisatab"
question from:https://stackoverflow.com/questions/64361041/how-to-check-if-a-string-contains-whitespace

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

assert!("Hello, world!".contains(char::is_whitespace));
assert!("Hello
".contains(char::is_whitespace));
assert!("Thisisatab".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!
";

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...