Is there an easy way to generate a lowercase and uppercase English alphabet in Rust?

This is what I am 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:

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

There are also no drawers, if possible.

+6
source share
4 answers

You cannot iterate over a char range directly, so with a little cast 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 by combining map and filter in 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<_>>(); 
+5
source

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 do not need to memorize ASCII numbers.

+6
source

You can convert int to char to a given base. Here is the code for 'a' to 'z' :

 use std::char; fn main() { let alphabet = (10..36).map(|i| char::from_digit(i, 36).unwrap()).collect::<Vec<_>>(); println!("{:?}", alphabet); } 

Ouput:

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

For the whole solution, you can create another one with uppercase and combine the two.

An example of the whole solution:

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

Speaking, I think it's easy to write a vector with literals.

+1
source

If for some reason (say, assignment) you do not need to generate characters, the simplest and shortest code is, of course, literally:

 fn main() { let alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; println!("{:?}", alpha); } 

If you need characters separately:

 fn main() { let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".chars(); // If you for some reason need a Vec: println!("{:?}", chars.collect::<Vec<_>>()); } 
0
source

Source: https://habr.com/ru/post/1270253/


All Articles