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.
This Rust program acts on str
references. We call the ASCII lowercase and uppercase functions first, and print the results with println
.
string
data and return a string
. This means we can call them on str
references, as no modifications occur.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
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.
make_ascii_lowercase
, the original data is modified in-place, so we must have a String
.to_string()
on the str
literal to create a String
, so that it can be modified in-place.mut
" keyword.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
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.
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.