Iteration thought alphabets

in c/c++ we can iteration thought alphabets using ```
for(char alphabet = 'a'; alphabet <='z'; alphabet++ )
how can we apply this in rust using for loop

1 Like

let a = "abcdefghijklmnopqrstuvwxyz".to_string;
for i in a.chars(){
print!(" {}",i);
}
i try one method
any other way to achieve this

fn main() {
    for i in 97u8..=122 {
        print!("{} ", i as char)
    }

    println!();

    // LOL
    println!("{}", (b'a'..=b'z').fold(String::new(), |acc, c| format!("{} {}", acc, c as char)));
    // LOL
    println!("{}", (97..=122).map(|i| (i as char).to_string()).collect::<Vec<_>>().join(" "));
    // LOL
    println!("{}", (0u8..26).fold(String::new(), |mut acc, i| { acc.push((i + 97) as char); acc }));
}
1 Like

In Rust 'a' is a UTF-8 character, in this case you probably want to iterate along ASCII characters, something like:

fn main() {
    for c in b'a'..=b'z' {
        println!("{}", c as char);
    }
}

Which is similar to what @AurevoirXavier replied, just using the byte representation of the characters instead of their numeric value.

6 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.