How to convert a Rust char to an integer so that '1' becomes 1?

Viewed 53461

I am trying to find the sum of the digits of a given number. For example, 134 will give 8.

My plan is to convert the number into a string using .to_string() and then use .chars() to iterate over the digits as characters. Then I want to convert every char in the iteration into an integer and add it to a variable. I want to get the final value of this variable.

I tried using the code below to convert a char into an integer:

fn main() {
    let x = "123";
    for y in x.chars() {
        let z = y.parse::<i32>().unwrap();
        println!("{}", z + 1);
    }
}

(Playground)

But it results in this error:

error[E0599]: no method named `parse` found for type `char` in the current scope
 --> src/main.rs:4:19
  |
4 |         let z = y.parse::<i32>().unwrap();
  |                   ^^^^^

This code does exactly what I want to do, but first I have to convert each char into a string and then into an integer to then increment sum by z.

fn main() {
    let mut sum = 0;
    let x = 123;
    let x = x.to_string();
    for y in x.chars() {
        // converting `y` to string and then to integer
        let z = (y.to_string()).parse::<i32>().unwrap();
        // incrementing `sum` by `z`
        sum += z;
    }
    println!("{}", sum);
}

(Playground)

5 Answers

If c is your character you can just write:

c as i32 - 0x30;

Test with:

let c:char = '2';
let n:i32 = c as i32 - 0x30;
println!("{}", n);

output:

2

NB: 0x30 is '0' in ASCII table, easy enough to remember!

Related