Convert a white space separated string int 2 digit int

fn to_vector(s: &str) -> Vec<u32> {
    let mut digits = Vec::new();
    for c in s.chars() {
        if let Some(digit) =c.to_digit(10) {
            digits.push(digit);
        }
    }
    digits
}
fn main() {
    let my_string = "12 34 45";
    let my_vec = to_vector(my_string);
    
    println!("{:?}", my_vec);
}

Output = [1, 2, 3, 4, 5, 6]
what I'm trying to get is [12, 34, 56]

Is there any particular reason you're going digit by digit? (Practice?)

This works for your stated use case:

fn to_vector(s: &str) -> Vec<u32> {
    s.split_whitespace()
        .filter_map(|sub| sub.parse().ok())
        .collect()
}

It ignores "words" that can't be parsed as u32, whether or not they contain some digits. (Your OP ignores all non-digits; your actual desired behavior for non-u32-values is unclear.)

1 Like

Thanks that helped. Particular reason? Practice is about the best answer I have. I'm teaching myself programming. Went through examples in Rust by Example and now I'm solving problems on Project Euler for fun. When I run into an issue I search docs and google. This had me searching a couple of days without getting into the math part.

2 Likes