How to remove all non-numeric characters from a string in Rust

1 Answer

0 votes
/// Removes all non-numeric characters from the input string slice,
/// returning a new String containing only ASCII digits (0-9).
/// 
/// @param input - The source string slice containing alphanumeric and special characters.
/// @return A new String with all non-numeric characters removed.
pub fn remove_non_numeric(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 standard ASCII digits
    // 3. Collect the filtered characters into a newly allocated String
    input
        .chars()
        .filter(|c| c.is_ascii_digit())
        .collect()
}

fn main() {
    // Test string provided
    let text = "123XYZ +9982-programming 10000000000001language";

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

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


/*
run:

Original: 123XYZ +9982-programming 10000000000001language
Cleaned:  123998210000000000001

*/

 



answered 1 day ago by avibootz

Related questions

...