How to convert ascii char to int like c/c++ in rust

Viewed 87

In c/c++, an ascii char can be converted to a number

int('a')

But how to do this in rust?

1 Answers

You can simply convert character to u32 this way: let code = 'a' as u32;. This will give you unicode value for specific character.

fn main() {
    let s = "0123";
    for c in s.chars() {
        println!("{c} -> {}", c as u32);
    }
}

Try it here

But if you are strictly require to work with ASCII not with Unicode, you can also check ascii crate

Related