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

这就是我到目前为止所做的事情:

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"]

如果可能的话也没有板条箱.

最佳答案
你不能直接迭代一系列的字符,所以通过一点点转换,我们可以这样做:

let alphabet = (b'A' .. b'z' + 1)      // 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>

或者,将地图和过滤器组合到filter_map中

let alphabet = (b'A' .. b'z' + 1 )                         // 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<_>>();   

我们迭代直到b’z’1,因为范围是非包容性的.如果你每晚都在使用#![feature(inclusive_range_syntax)]并写

(b'A' ..= b'z')  

代替.

转载注明原文:string – 有没有一种简单的方法可以在Rust中生成小写和大写英文字母? - 代码日志