将字符解析为 u32 [英] Parsing a char to u32

查看:49
本文介绍了将字符解析为 u32的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如问题所述,我如何实现这一目标?

As the questions states, how do I achieve this?

如果我有这样的代码:

let a = "29";
for c in a.chars() {
    println!("{}", c as u32);
}

我得到的是 2 和 9 的 unicode 代码点:

What I obtain is the unicode codepoints for 2 and 9:

  • 50
  • 57

我想要的是将这些字符解析为实际数字.

What I want is to parse those characters into the actual numbers.

推荐答案

char::to_digit(radix) 就是这样做的.radix 表示基数",即十进制为 10,十六进制为 16,等等:

char::to_digit(radix) does that. radix denotes the "base", i.e. 10 for the decimal system, 16 for hex, etc.:

let a = "29";
for c in a.chars() {
    println!("{:?}", c.to_digit(10));
}

它返回一个Option,所以你需要unwrap()它,或者更好:expect("that's no number!").您可以在 Rust 书的相应章节.

It returns an Option, so you need to unwrap() it, or better: expect("that's no number!"). You can read more about proper error handling in the appropriate chapter of the Rust book.

这篇关于将字符解析为 u32的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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