41
votes

I've been looking into how you convert a string to upper case in Rust. The most optimal way I've figured out so far is this:

let s = "smash";
let asc = s.to_ascii().to_upper();
println!("Hulk {:s}", asc.as_str_ascii());

Is there a less verbose way to do it?

Note: This question is specifically targetted at Rust 0.9. There was another related answer available at the time of asking, but it was for Rust 0.8 which has significant syntax differences and so not applicable.

3

3 Answers

46
votes

If you use the std::string::String type instead of &str, there is a less verbose way with the additional benefit of Unicode support:

fn main() {
    let test_str = "übercode"; // type &str

    let uppercase_test_string = test_str.to_uppercase(); // type String

    let uppercase_test_str = uppercase_test_string.as_str(); // back to type &str

    println!{"{}", test_str};
    println!{"{}", uppercase_test_string};
    println!{"{}", uppercase_test_str};
}
16
votes

I think the recommended way is to use String::to_ascii_uppercase:

fn main() {
    let r = "smash".to_ascii_uppercase();
    println!("Hulk {}!", r); // Hulk SMASH!

    //or one liner
    println!("Hulk {}!", "smash".to_ascii_uppercase());
}
2
votes

In Rust 1.2.0, str::to_uppercase() was added.

fn main() {
    let s = "smash";
    println!("Hulk {}", s.to_uppercase());
}