Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String of numbers to array of numbers

I’m learning Rust and am messing around with conversions of types because I need it for my first program.

Basically I’m trying to convert a singular string of numbers into an array of numbers.

eg. "609" -> [6,0,9]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const RADIX: u32 = 10;
let lines: Vec<String> = read_lines(filename);

let nums = lines[0].chars().map(|c| c.to_digit(RADIX).expect("conversion error"));

println!("Line: {:?}, Converted: {:?}", lines[0], nums);

I tried the above and the output is as follows:

Line: "603", Converted: Map { iter: Chars(['6', '0', '3']) }

Which I assume isn’t correct. I’d need it to be just a pure array of integers so I can perform operations with it later.

>Solution :

You’re almost there, add the type ascription to nums:

let nums: Vec<u32> = ...

and end the method chain with .collect() to turn it into a vector of digits.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading