Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

rust

This is what I'm doing so far:

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);
}

Output is:

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

Also no crates if possible.

like image 552
GoldenChrysanthem Avatar asked Jul 27 '17 06:07

GoldenChrysanthem


People also ask

How do you change to lowercase in Rust?

In Rust, the to_lowercase() method is used to convert a character or string to lowercase. It converts any letter that is not in lowercase to lowercase.

How do you capitalize chars in Rust?

Rust provides two methods to convert an ASCII lowercase character to uppercase: to_ascii_uppercase() and make_ascii_uppercase() .

How do you set the alphabet in uppercase?

To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and press SHIFT + F3 until the case you want is applied.


2 Answers

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<_>>();
like image 199
Jan Hohenheim Avatar answered Sep 19 '22 09:09

Jan Hohenheim


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.

like image 43
ljedrz Avatar answered Sep 17 '22 09:09

ljedrz