Can't fins a way to cast a char into u8

Viewed 1151

I've been trying to replace every letter in a given string slice with its position in the alphabet ("A" with "1", "B" with "2" etc).

fn alphabet_position(text: &str) -> String {
    let s = text
        .chars()
        .into_iter()
        .filter(|&c| c.is_alphabetic())
        .map(|c| c.to_ascii_uppercase())
        .map(|c| c as u8)
        .map(|c| (c - 64u8) as char)
        .collect();
    s
}
1 Answers

Try the u8::to_string() function.

fn alphabet_position(text: &str) -> String {
    let s = text
        .chars()
        .into_iter()
        .filter(|&c| c.is_alphabetic())
        .map(|c| c.to_ascii_uppercase())
        .map(|c| c as u8)
        .map(|c| (c - 64u8).to_string())
        .collect();
    s
}

Rust Playground

Related