Dash83
Dash83

Reputation: 1468

Parsing a char to u32

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:

What I want is to parse those characters into the actual numbers.

Upvotes: 32

Views: 43493

Answers (2)

hansaplast
hansaplast

Reputation: 11593

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.

Upvotes: 43

ljedrz
ljedrz

Reputation: 22273

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.

Upvotes: 15

Related Questions