gpt4 book ai didi

string - 有没有一种简单的方法可以在 Rust 中生成小写和大写英文字母表?

转载 作者:行者123 更新时间:2023-11-29 07:47:16 25 4
gpt4 key购买 nike

这是我目前正在做的:

fn main() {
let a = (0..58).map(|c| ((c + 'A' as u8) as char).to_string())
.filter(|s| !String::from("[\\]^_`").contains(s) )
.collect::<Vec<_>>();

println!("{:?}", a);
}

输出是:

["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

如果可能的话也没有 crate 。

最佳答案

您不能直接遍历 char 的范围,因此通过一些转换我们可以做到这一点:

let alphabet = (b'A'..=b'z')           // Start as u8
.map(|c| c as char) // Convert all to chars
.filter(|c| c.is_alphabetic()) // Filter only alphabetic chars
.collect::<Vec<_>>(); // Collect as Vec<char>

或者,将 mapfilter 组合成 filter_map

let alphabet = (b'A'..=b'z')                               // Start as u8
.filter_map(|c| {
let c = c as char; // Convert to char
if c.is_alphabetic() { Some(c) } else { None } // Filter only alphabetic chars
})
.collect::<Vec<_>>();

关于string - 有没有一种简单的方法可以在 Rust 中生成小写和大写英文字母表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45343345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com