How to remove all letters from an alphanumeric string in Rust

1 Answer

0 votes
/// Removes all alphabetical letters from the input string slice,
/// returning a new String with letters removed (retaining digits, spaces, and symbols).
/// 
/// @param input - The source string slice containing alphanumeric and special characters.
/// @return A new String with all alphabetical letters removed.
pub fn remove_letters(input: &str) -> String {
    // 1. Convert the string into a Unicode scalar value (char) iterator via .chars()
    // 2. Filter the iterator to keep only characters that are NOT alphabetical letters
    // 3. Collect the filtered characters into a newly allocated String
    input
        .chars()
        .filter(|c| !c.is_alphabetic())
        .collect()
}

fn main() {
    // Test string provided
    let text = "abc123XYZ456programming789";

    // Process the string
    let cleaned_text = remove_letters(text);

    // Output results
    println!("Original: {}", text);
    println!("Cleaned:  {}", cleaned_text);
}



/*
run:

Original: abc123XYZ456programming789
Cleaned:  123456789

*/

 



answered 1 day ago by avibootz
...