Is there a simple way to generate the lowercase and uppercase English alphabet in Rust?

There are many options; you can do the following:

fn main() {
    let alphabet = String::from_utf8(
        (b'a'..=b'z').chain(b'A'..=b'Z').collect()
    ).unwrap();

    println!("{}", alphabet);
}

This way you don't need to remember the ASCII numbers.


You cannot iterate over a range of chars directly, so with a little casting we can do this:

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>

or, combining the map and filter into 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<_>>();

Tags:

String

Rust