[英]How do I subtract one character from another in Rust?
在 Java 中,我可以做到这一点。
int diff = 'Z' - 'A'; // 25
我在 Rust 中尝试过同样的方法:
fn main() {
'Z' - 'A';
}
但编译器抱怨:
error[E0369]: binary operation `-` cannot be applied to type `char`
--> src/main.rs:2:5
|
2 | 'Z' - 'A';
| ^^^^^^^^^
|
= note: an implementation of `std::ops::Sub` might be missing for `char`
如何在 Rust 中进行等效操作?
该操作在 Unicode 世界中毫无意义,而在 ASCII 世界中几乎没有意义,这就是 Rust 不直接提供它的原因,但根据您的用例,有两种方法可以做到这一点:
'Z' as u32 - 'A' as u32
b'Z' - b'A'
数学在 unicode 中并非毫无意义,它错过了 utf-8 最令人惊奇的特性。
任何高位为 0 的 7 位字符都是有效的 us-ascii,一个 7 位的 us-ascii doc 是有效的 utf-8。 您可以将 utf-8 视为 us-ascii 字节,前提是所有比较和数学处理都处理低于 127 的值。这是 utf-8 的设计,C 代码往往可以正常工作,但是 rust 使这变得复杂。
给定一个字符串value: &str
抓取字节as_bytes()
for byt in value.as_bytes() {
let mut c = *byt; // c is u8 (unsigned byte)
// if we are dealing with us-ascii chars...
if c >= b'A' && c <= b'Z' {
// math works, this converts to us-ascii lowercase
c = c + 32;
}
// to treat the u8 as a rust char cast it
let ch = c as char;
// now you can write sane code like
if ch == ':' || ch == ' ' || ch == '/' {
....
// but you cant do math anymore
这个数学不是毫无意义的, +32
是 AZ 的一个方便的小写函数,这是对 utf-8 字符的有效处理。
utf-8 中的a + 1 = b
并非偶然。 Ascii-beticaly 排序可能与现实世界的字母排序不同,但它仍然很有用,因为它在常见的字符范围内表现良好。
ascii 中的'3' + 1 = '4'
并非毫无意义。
您不会将字符串 utf-8 分解为字节,即使字符串中有笑脸便便,像if (c == 'a')
这样的简单代码也可以工作。
在 Rust 的 char 上做数学是不可能的,这是一种耻辱。
对 utf-8 字符串的一个字节进行数学运算与以往一样有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.