user16541277
user16541277

Reputation:

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]

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.

Upvotes: 0

Views: 777

Answers (1)

orlp
orlp

Reputation: 117791

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.

Upvotes: 3

Related Questions