Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The English alphabet as a vector of characters in Rust

Tags:

rust

The title says it all. I want to generate the alphabet as a vector of characters. I did consider simply creating a range of 97-122 and converting it to characters, but I was hoping there would be a nicer looking way, such as Python's string.ascii_lower.

The resulting vector or string should have the characters a-z.

like image 698
Johanna Larsson Avatar asked Sep 27 '13 15:09

Johanna Larsson


2 Answers

Hard-coding this sort of thing makes sense, as it can then be a compiled constant, which is great for efficiency.

static ASCII_LOWER: [char; 26] = [
    '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',
];

(Decide for yourself whether to use static or const.)

This is pretty much how Python does it in string.py:

lowercase = 'abcdefghijklmnopqrstuvwxyz'
# ...
ascii_lowercase = lowercase
like image 121
Chris Morgan Avatar answered Nov 15 '22 10:11

Chris Morgan


Collecting the characters of a str doesn't seem like a bad idea...

let alphabet: Vec<char> = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".chars().collect();
like image 45
Gark Garcia Avatar answered Nov 15 '22 10:11

Gark Garcia