As the questions states, how do I achieve this?
If I have a code like this:
let a = "29"; for c in a.chars() { println!("{}", c as u32); } What I obtain is the unicode codepoints for 2 and 9:
- 50
- 57
What I want is to parse those characters into the actual numbers.
02 Answers
char::to_digit(radix) does that. radix denotes the "base", i.e. 10 for the decimal system, 16 for hex, etc.:
let a = "29"; for c in a.chars() { println!("{:?}", c.to_digit(10)); } It returns an Option, so you need to unwrap() it, or better: expect("that's no number!"). You can read more about proper error handling in the appropriate chapter of the Rust book.
Well, you can always use the following hacky solution:
fn main() { let a = "29"; for c in a.chars() { println!("{}", c as u32 - 48); } } ASCII digits are encoded with values from 48 to 57, so when you have a string containing characters 2 and 9 and attempt to interpret them as integers, you get 50 and 57. To get their expected values you just need to subtract 48 from them.
1