rust - 找不到将 char 转换为 u8 的方法

标签 rust

我一直在尝试将给定字符串切片中的每个字母替换为其在字母表中的位置(“A”替换为“1”,“B”替换为“2”等)。

fn alphabet_position(text: &str) -> String {
    let s = text
        .chars()
        .into_iter()
        .filter(|&c| c.is_alphabetic())
        .map(|c| c.to_ascii_uppercase())
        .map(|c| c as u8)
        .map(|c| (c - 64u8) as char)
        .collect();
    s
}

最佳答案

试试 u8::to_string()功能。

fn alphabet_position(text: &str) -> String {
    let s = text
        .chars()
        .into_iter()
        .filter(|&c| c.is_alphabetic())
        .map(|c| c.to_ascii_uppercase())
        .map(|c| c as u8)
        .map(|c| (c - 64u8).to_string())
        .collect();
    s
}

Rust Playground

关于rust - 找不到将 char 转换为 u8 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66576556/

相关文章:

rust - 扩展 Rust 生命周期

rust - 检查一个数字是否可以精确表示为 `f32`

closures - 函数类型vs闭包类型

collections - 迭代时无法分配给不可变的索引内容

string - 在 Rust 中,有没有办法使用 Windows 约定在 r## #"..."### 中创建文字换行符?

rust - 如何在不拥有 `self` 的方法中对 Vec 进行分区?

使用 clang 与 C 链接时缺少 Rust 目标文件

rust - 在 Rust 中寻找方法实现的来源?

rust - 在 vec 排水管上捕捉 panic

linux - 为什么 Valgrind 没有显示 Rust 程序的分配?