Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 583
Greg Malcolm Avatar asked Feb 10 '14 05:02

Greg Malcolm


People also ask

How do you change a string into a upper case?

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.

How do you capitalize chars in Rust?

Rust provides two methods to convert an ASCII lowercase character to uppercase: to_ascii_uppercase() and make_ascii_uppercase() .

How do you convert a string to lowercase in Rust?

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.

How do you convert string to Rust?

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.


2 Answers

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}; } 
like image 132
Codetoffel Avatar answered Sep 23 '22 23:09

Codetoffel


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()); } 
like image 30
Daniel Fath Avatar answered Sep 22 '22 23:09

Daniel Fath