我试图找到给定数字的所有数字的总和,如134给出8.
我的计划是通过将数字转换为.to_string()使用数来迭代数字.chars(),然后使用char迭代数字.然后我想将char迭代中的每个转换为a char并添加到变量中.我想得到这个变量的最终值.
我尝试使用下面的代码将a sum转换为z(Playground):
fn main() {
let x = "123";
for y in x.chars() {
let z = y.parse::<i32>().unwrap();
println!("{}", z + 1);
}
}
Run Code Online (Sandbox Code Playgroud)
但它会导致此错误:
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();
| ^^^^^
Run Code Online (Sandbox Code Playgroud)
如何将a 134转换为整数?
下面的代码完全符合我的要求(Playground):
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);
}
Run Code Online (Sandbox Code Playgroud)
但首先我必须转换8成字符串,然后转换成整数递增.to_string()的.chars().有没有办法直接转换char成整数?
Pav*_*hov 14
你需要的方法是char::to_digit.它转换char为它在给定基数中表示的数字.
您还可以使用方便Iterator::sum地计算序列的总和:
fn main() {
const RADIX: u32 = 10;
let x = "134";
println!("{}", x.chars().map(|c| c.to_digit(RADIX).unwrap()).sum::<u32>());
}
Run Code Online (Sandbox Code Playgroud)
my_char as u32 - '0' as u32
Run Code Online (Sandbox Code Playgroud)
现在,关于这个答案还有很多东西需要解开。
它起作用是因为 ASCII(以及 UTF-8)编码具有按升序排列的阿拉伯数字 0-9。您可以获得标量值并减去它们。
但是,对于这个范围之外的值,它应该怎么做?如果您提供,会发生什么'p'?它返回 64.'.'呢?这会恐慌。而'?'将返回9781。
字符串不仅仅是字节包。它们是 UTF-8 编码的,你不能忽视这个事实。每个都char可以保存任何 Unicode 标量值。
这就是为什么字符串是问题的错误抽象。
从效率的角度来看,分配字符串似乎效率低下。Rosetta Code 有一个使用迭代器的例子,它只执行数字运算:
struct DigitIter(usize, usize);
impl Iterator for DigitIter {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.0 == 0 {
None
} else {
let ret = self.0 % self.1;
self.0 /= self.1;
Some(ret)
}
}
}
fn main() {
println!("{}", DigitIter(1234, 10).sum::<usize>());
}
Run Code Online (Sandbox Code Playgroud)
如果c是你的角色,你可以这样写:
c as i32 - 0x30;
Run Code Online (Sandbox Code Playgroud)
测试:
let c:char = '2';
let n:i32 = c as i32 - 0x30;
println!("{}", n);
Run Code Online (Sandbox Code Playgroud)
输出:
2
Run Code Online (Sandbox Code Playgroud)
注意:0x30 在 ASCII 表中是“0”,很容易记住!
| 归档时间: |
|
| 查看次数: |
10606 次 |
| 最近记录: |