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.
Performing the . upper() method on a string converts all of the characters to uppercase, whereas the lower() method converts all of the characters to lowercase.
Rust provides two methods to convert an ASCII lowercase character to uppercase: to_ascii_uppercase() and make_ascii_uppercase() .
In Rust, the to_lowercase() method is used to convert a character or string to lowercase. It converts any letter that is not in lowercase to lowercase.
String to Integer To convert a string to an integer in Rust, use parse() function. The parse function needs to know what type, which can be specified on the left-side of assignment like so: let str = "123"; let num: i32 = str.
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}; }
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()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With