简体   繁体   English

在 Rust 中将字符串转换为大写的最简单方法是什么?

[英]What is the simplest way to convert a string to upper case in Rust?

I've been looking into how you convert a string to upper case in Rust.我一直在研究如何在 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.注意:这个问题专门针对 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.在询问时还有另一个相关的答案可用,但它是针对 Rust 0.8 的,它具有显着的语法差异,因此不适用。

If you use the std::string::String type instead of &str , there is a less verbose way with the additional benefit of Unicode support: 如果你使用std::string::String类型而不是&str ,那么Unicode支持的额外好处就是一种不那么冗长的方式:

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

I think the recommended way is to use String::to_ascii_uppercase : 我认为推荐的方法是使用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());
}

In Rust 1.2.0, str::to_uppercase() was added.在 Rust 1.2.0 中,添加了str::to_uppercase()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM