rust 如何转换一系列分隔的“数字”?

igetnqfo  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(105)

向量m包含从4857的“数字”,48对应于0491等。数字按顺序由13, 10的出现分隔。如何在下面的例子中得到n的结果[1073, 8705]

fn main() {

  let m: Vec<u8> = vec![49, 48, 55, 51, 13, 10, 56, 55, 48, 53, 13, 10];
  let mut n: Vec<u32> = vec![];

  println!("m = {:?}", m);
  println!("n = {:?}", n);

  //  ...
  
  println!("n = {:?}", n); // ? how get: [1073, 8705]
}

/*
0 - 48
1 - 49
2 - 50
3 - 51
4 - 52
5 - 53
6 - 54
7 - 55
8 - 56
9 - 57
*/

字符串
play.rust-lang.org

x8diyxa7

x8diyxa71#

尽管由于使用字符串而对运行时有很小的影响,但我仍然更喜欢Rust的成熟解析功能:

let v: Vec<u8> = vec![49, 48, 55, 51, 13, 10, 56, 55, 48, 53, 13, 10];
let s: String = String::from_utf8(v).unwrap();

let n: Vec<_> = s.lines().map(|n| n.parse::<u32>().unwrap()).collect();
println!("{n:?}");

字符串
对于字符串数组,将n.parse::<u32>()更改为n.parse::<String>()
Playground

hmtdttj4

hmtdttj42#

你不需要遍历String,你可以手动解析。

fn main() {
    let m = vec![49_u8, 48, 55, 51, 13, 10, 56, 55, 48, 53, 13, 10];

    let mut curr_num = 0_u32;
    let mut curr_is_nonempty = false;
    let mut nums = Vec::new();

    let mut i = 0;
    while i < m.len() {
        if &m[i..i + 2] == &[13, 10] {
            nums.push(curr_num);
            curr_num = 0;
            curr_is_nonempty = false;
            i += 2;
            continue;
        }

        let val = (m[i] - b'0') as u32;
        curr_num = 10 * curr_num + val;
        curr_is_nonempty = true;

        i += 1;
    }

    if curr_is_nonempty {
        nums.push(curr_num);
    }

    println!("m = {:?}", m);
    println!("n = {:?}", nums);
}

字符串

相关问题