Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if string only contains set of characters in Rust?

What is the idiomatic way in Rust to check if a string only contains a certain set of characters?

like image 683
Aart Stuurman Avatar asked Jul 17 '18 23:07

Aart Stuurman


People also ask

How to check if String contains substring Rust?

The easiest way to check if a Rust string contains a substring is to use String::contains method. The contains method Returns true if the given pattern matches a sub-slice of this string slice. The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

Is str growable in Rust?

There are two types of strings in Rust: String and &str . A String is stored as a vector of bytes ( Vec<u8> ), but guaranteed to always be a valid UTF-8 sequence. String is heap allocated, growable and not null terminated.

How big is a String in Rust?

A String is always 24 bytes.


2 Answers

You'd use all to check that all characters are alphanumeric.

fn main() {
    let name = String::from("Böb");
    println!("{}", name.chars().all(char::is_alphanumeric));
}
  • chars returns an iterator of characters.
  • all returns true if the function is true for all elements of the iterator.
  • is_alphanumeric checks if its alphanumeric.

For arbitrary character sets you can pass whatever function or code block you like to all.

Interestingly, the corresponding methods on str were explicitly removed for subtle Unicode reasons.

like image 163
Schwern Avatar answered Oct 13 '22 12:10

Schwern


There is is_alphanumeric():

fn main() {
    println!("{}", "abcd".chars().all(|x| x.is_alphanumeric()));
}
like image 20
Stargateur Avatar answered Oct 13 '22 11:10

Stargateur