To remove special characters from a string in Rust, you can use the chars() method to filter characters based on alphanumeric and space conditions.
In this example,
str1
with a value of "Hello! World!"
.chars()
method and check if each character is alphanumeric or a space.result
.result
.fn main() {
let str1 = String::from("Hello! World!");
let result: String = str1.chars().filter(|&c| c.is_alphanumeric() || c == ' ').collect();
println!("Modified string: {}", result);
}
Modified string: Hello World
In this example,
str2
with a value of "apple@banana"
.chars()
method and check if each character is alphanumeric or a space.result
.result
.fn main() {
let str2 = String::from("apple@banana");
let result: String = str2.chars().filter(|&c| c.is_alphanumeric() || c == ' ').collect();
println!("Modified string: {}", result);
}
Modified string: applebanana
In this tutorial, we learned How to Remove Special Characters from a String in Rust language with well detailed examples.