How to extract all digits from a string in Rust

1 Answer

0 votes
/*
    extract_digits
    --------------
    Scans the input string and collects only characters
    that are recognized as digits by Rust's Unicode-aware
    classification (`char::is_ascii_digit` or `char::is_numeric`).

    Here we use `is_ascii_digit` because the example input
    contains only ASCII digits, and it is slightly faster.
*/
fn extract_digits(s: &str) -> String {
    // Use an iterator pipeline to filter and collect digits.
    // This is efficient, expressive, and avoids manual loops.
    let digits = s.chars()
        .filter(|c| c.is_ascii_digit())
        .collect::<String>();

    digits
}

fn main() {
    // Example input string
    let str = "5 rust8go 9001 c c++ 17python";

    // Extract digits
    let digits = extract_digits(str);

    // Display results
    println!("Original: {}", str);
    println!("Digits:   {}", digits);
}



/*
run:

Original: 5 rust8go 9001 c c++ 17python
Digits:   58900117

*/

 



answered Sep 17 by avibootz
...