这就是我到目前为止所做的事情:
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"]
如果可能,也没有包装箱。
答案 0 :(得分:8)
有很多选择;你可以做到以下几点:
SonarQube
这样您就不需要记住ASCII码了。
答案 1 :(得分:5)
你不能直接迭代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>
或将map
和filter
合并到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<_>>();
答案 2 :(得分:1)
您可以将int转换为给定基数中的char。这里是'a'
到'z'
的代码:
use std::char;
fn main() {
let alphabet = (10..36).map(|i| char::from_digit(i, 36).unwrap()).collect::<Vec<_>>();
println!("{:?}", alphabet);
}
输出继电器:
['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']
对于整个解决方案,您可以使用大写创建另一个解决方案,并将两者连接起来。
整个解决方案的示例:
use std::char;
fn main() {
let mut lowercase = (10..36).map(|i| char::from_digit(i, 36).unwrap()).collect::<Vec<_>>();
let mut alphabet = lowercase.iter().map(|c| c.to_uppercase().next().unwrap()).collect::<Vec<_>>();
alphabet.append(&mut lowercase);
println!("{:?}", alphabet);
}
话虽如此,我认为用文字编写矢量更容易。
答案 3 :(得分:1)
除非你出于某种原因(例如,作业)需要实际生成字符,否则最简单,最短的代码当然只是一个文字:
fn main() {
let alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
println!("{:?}", alpha);
}
如果您需要单独的字符:
fn main() {
let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".chars();
// If you for some reason need a Vec:
println!("{:?}", chars.collect::<Vec<_>>());
}
答案 4 :(得分:0)
for alphabet in 'a'..='z' {
println!("{}", alphabet );
}
它以小写形式打印所有字母。