Parsing a char to u32

As the questions say, 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 get are the unicode code pages for 2 and 9:

  • fifty
  • 57

I want these characters to be displayed in actual numbers.

+4
source share
2 answers

char::to_digit(radix)doing this. radixstands for "base", i.e. 10 for decimal, 16 for hex, etc .:

let a = "29";
for c in a.chars() {
    println!("{:?}", c.to_digit(10));
}

He returns Option, so you need unwrap()it, or better expect("that no number!"). You can learn more about correct error handling in the relevant chapter of Rust .

+9
source

Well, you can always use the following hacker solution:

fn main() {
    let a = "29";
    for c in a.chars() {
        println!("{}", c as u32 - 48);
    }
}

ASCII 48 57, , , 2 9, , 50 57. , 48 .

+1

Source: https://habr.com/ru/post/1665234/


All Articles