How can I convert a string of numbers to an array or vector of integers in Rust?

后端 未结 3 390
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 10:57

I\'m writing on STDIN a string of numbers (e.g 4 10 30 232312) and I want to read that and convert to an array (or a vector) of integers, but I can\'t find the

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 11:26

    Safer version. This one skips failed parses so that failed unwrap doesn't panic. Use read_line for reading single line.

    let mut buf = String::new();
    
    // use read_line for reading single line 
    std::io::stdin().read_to_string(&mut buf).expect("");
    
    // this one skips failed parses so that failed unwrap doesn't panic
    let v: Vec = buf
        .split_whitespace() // split string into words by whitespace
        .filter_map(|w| w.parse().ok()) // calling ok() turns Result to Option so that filter_map can discard None values
        .collect(); // collect items into Vector. This determined by type annotation.
    

    You can even read Vector of Vectors like this.

    let stdin = io::stdin();
    let locked = stdin.lock();
    let vv: Vec> = locked.lines()
        .filter_map(
            |l| l.ok().map(
                |s| s.split_whitespace()
                     .filter_map(|word| word.parse().ok())
                     .collect()))
        .collect();
    

    Above one works for inputs like

    2 424 -42 124
    42 242 23 22 241
    24 12 3 232 445
    

    then turns them it into

    [[2, 424, -42, 124],
    [42, 242, 23, 22, 241],
    [24, 12, 3, 232, 445]]
    

    filter_map accepts a closure that returns Option and filters out all Nones.

    ok() turns Result to Option so that errors can be filtered in this case.

提交回复
热议问题