簡體   English   中英

如何在 Rust 中從另一個字符中減去一個字符?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM