What is the idiomatic way in Rust to check if a string only contains a certain set of characters?
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.
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.
A String is always 24 bytes.
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.
There is is_alphanumeric():
fn main() {
println!("{}", "abcd".chars().all(|x| x.is_alphanumeric()));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With