How to split/convert a string into vector of u16

I am having strings like this one :
"38929|38916|36900|39766|36922|38930|40492|........."
I want to create a Vec from this string.
How do I do this efficiently? (I have got some 50000 such strings each having about 70 (varying) numbers.)
Thanks

See:

EDIT: link to thread, not solution, since there are more/better suggestions and discussion.

1 Like

50 000 strings is nothing. You can just use the most obvious solution

let v: Vec<usize> = s.split('|').map(|num| num.parse()).collect()?;

and it should be done in a few seconds.

5 Likes

May be I have not totally understood your solution. I tried to run that but it is throwing errors.
Can you please take an example string from above and write the formula?
No rush..........Do that in your free time.
Thanks

// or actually read from a file?
let string = "38929|38916|36900|39766";
let nums = string
    .split('|')
    .map(|num| num.parse::<u32>())
    .collect::<Result<Vec<u32>, _>>()
    .expect("FIXME handle a number parsing error here");
assert_eq!(nums, [38929, 38916, 36900, 39766]);

Playground
Edit: use u32 because u16 only supports numbers up to 65535 and it looks like you might have bigger numbers

2 Likes

if you just want a mutable vector you can do this and then later apply a filter.

fn main() {
    let inputstr = String::from("38929|38916|36900|39766|36922|38930|40492|.........");
    let vec = inputstr.split("|").collect::<Vec<&str>>();
    println!("{:?}", vec);
}