如何将 Rust 字符转换为整数,使 '1' 变为 1? [英] How to convert a Rust char to an integer so that '1' becomes 1?

查看:102
本文介绍了如何将 Rust 字符转换为整数,使 '1' 变为 1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出给定数字的数字之和.例如,134 将给出 8.

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

我的计划是使用 .to_string() 将数字转换为字符串,然后使用 .chars() 将数字作为字符进行迭代.然后我想将迭代中的每个 char 转换为一个整数并将其添加到一个变量中.我想得到这个变量的最终值.

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.

我尝试使用下面的代码将 char 转换为整数:

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);
    }
}

(游乐场)

但它导致了这个错误:

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();
  |                   ^^^^^

这段代码完全符合我的要求,但首先我必须将每个 char 转换为字符串,然后转换为整数,然后通过 递增 sum>z.

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);
}

(游乐场)

推荐答案

你需要的方法是 char::to_digit.它将 char 转换为它在给定基数中表示的数字.

The method you need is char::to_digit. It converts char to a number it represents in the given radix.

你也可以使用 Iterator::sum 方便地计算一个序列的和:

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::<u32>());
}

这篇关于如何将 Rust 字符转换为整数,使 '1' 变为 1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆