snippetrustCritical
How to convert a Rust char to an integer so that '1' becomes 1?
Viewed 0 times
howintegerconvertbecomesrustcharthat
Problem
I am trying to find the sum of the digits of a given number. For example,
My plan is to convert the number into a string using
I tried using the code below to convert a
(Playground)
But it results in this error:
This code does exactly what I want to do, but first I have to convert each
(Playground)
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::().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::().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::().unwrap();
// incrementing `sum` by `z`
sum += z;
}
println!("{}", sum);
}(Playground)
Solution
The method you need is
You can also use
char::to_digit. It converts char to a number it represents in the given radix. You can also use
Iterator::sum to calculate sum of a sequence conveniently:fn main() {
const RADIX: u32 = 10;
let x = "134";
println!("{}", x.chars().map(|c| c.to_digit(RADIX).unwrap()).sum::());
}Code Snippets
fn main() {
const RADIX: u32 = 10;
let x = "134";
println!("{}", x.chars().map(|c| c.to_digit(RADIX).unwrap()).sum::<u32>());
}Context
Stack Overflow Q#43983414, score: 124
Revisions (0)
No revisions yet.