Rust to lowercase ExampleUse the to lowercase and to uppercase functions to transform casing in strings. Change string data in-place.
To lowercase. In Rust we can transform strings from lowercase to uppercase, and the opposite, with built-in functions. It is also possible to transform strings in-place, avoiding an allocation.
For ASCII strings, we have more options. The "make" functions only are available for ASCII, as transforming the case of ASCII data never changes its length.
First example. This program acts on str references. We call the ASCII lowercase and uppercase functions first, and print the results with println.
Tip The "to" functions copy the string data and return a string. This means we can call them on str references, as no modifications occur.
Rust program that uses lowercase, uppercase
fn main() { let value = "BIRD"; // Lowercase and uppercase the string. let result = value.to_ascii_lowercase(); println!("{}", result); let result = value.to_ascii_uppercase(); println!("{}", result); // This has the same result. let result = value.to_lowercase(); println!("{}", result); let result = value.to_uppercase(); println!("{}", result); }
bird BIRD bird BIRD
Make lowercase. For the "make" methods, we can only act on ASCII data. A String is needed, and we cannot call make_ascii_lowercase() on a str reference.
Info With make_ascii_lowercase, the original data is modified in-place, so we must have a String.
To string We call to_string() on the str literal to create a String, so that it can be modified in-place.
Mut We must make the variable we call these functions on mutable, so we use the "mut" keyword.
Rust program that uses make ascii lowercase
fn main() { let mut value = "SNOW".to_string(); // Modify the string in-place. value.make_ascii_lowercase(); println!("{}", value); value.make_ascii_uppercase(); println!("{}", value); }
snow SNOW
Performance review. For performance, modifying existing data (as with make_ascii_lowercase) is faster, but a String is needed. So the opportunity for optimization is fairly narrow here.
A summary. The standard library in Rust is powerful, well-designed and fairly extensive. It allows us to lowercase and uppercase strings in many ways, and provides some optimizations.
© 2007-2022 sam allen.
see site info on the changelog.