To check if a string contains only alphabets and numbers in Rust, you can use the chars
iterator and the is_alphanumeric
method.
In this example,
contains_only_alphabets_and_numbers
that takes a string reference as input.chars
iterator.is_alphanumeric
method.true
, otherwise false
.fn contains_only_alphabets_and_numbers(s: &str) -> bool {
s.chars().all(|c| c.is_alphanumeric())
}
fn main() {
let s = "Hello123";
let result = contains_only_alphabets_and_numbers(s);
println!("String contains only alphabets and numbers: {}", result);
}
String contains only alphabets and numbers: true
In this tutorial, we learned How to Check if String contains only Alphabets and Numbers in Rust language with well detailed examples.