To check if a string contains only alphabets in Rust, you can iterate through each character and check if it is an alphabet using functions like char::is_alphabetic
.
In this example,
str
with a value of "Hello123"
.is_alphabetic
method of the char
type.contains_only_alphabets
to true
, otherwise false
.fn main() {
let str = String::from("Hello123");
let mut contains_only_alphabets = true;
for c in str.chars() {
if !c.is_alphabetic() {
contains_only_alphabets = false;
break;
}
}
println!("String contains only alphabets: {}", contains_only_alphabets);
}
String contains only alphabets: false
In this tutorial, we learned How to Check if String contains only Alphabets in Rust language with well detailed examples.