To keep only alphabets in a string in Rust, you can use iterators and filter out non-alphabetic characters using the 'is_alphabetic' method.
In this example,
str1
with a value of "Hello123 World"
.chars()
method on the string.filter()
method on the iterator with a closure that checks if each character is alphabetic using the is_alphabetic()
method.result1
.result1
.fn main() {
let str1 = "Hello123 World";
let result1: String = str1.chars()
.filter(|&c| c.is_alphabetic())
.collect();
println!("Modified string: {}", result1);
}
Modified string: HelloWorld
In this example,
str2
with a value of "apple@banana"
.chars()
method on the string.filter()
method on the iterator with a closure that checks if each character is alphabetic using the is_alphabetic()
method.result2
.result2
.fn main() {
let str2 = "apple@banana";
let result2: String = str2.chars()
.filter(|&c| c.is_alphabetic())
.collect();
println!("Modified string: {}", result2);
}
Modified string: applebanana
In this tutorial, we learned How to keep only Alphabets in a String in Rust language with well detailed examples.