How to Convert Strings into Uppercase and Lower case in Rust example
This program demonstrates multiple ways to convert a string to uppercase in Rust, along with examples.
For example, if the given string is “Hello”, the output for uppercase would be “HELLO”.
How to Convert a Lowercase String to Uppercase in Rust?
Let’s explore how to convert a string to uppercase in Rust.
There are several methods to achieve this.
Using the to_uppercase Function
The
to_uppercase
function returns the uppercase version of a string.Here’s an example program:
fn main() { let str = "Hello World"; println!(" {}", str.to_uppercase()); }
Output:
HELLO WORLD
Using the to_ascii_uppercase Function
The
to_ascii_uppercase
function returns the uppercase version of ASCII characters in a string. Non-ASCII characters remain unchanged.For example, ASCII characters such as
a to z
are converted toA to Z
. Non-ASCII characters are not changed and return the same.Here is an example program
fn main() { let str = "Hello World"; println!(" {}", str.to_ascii_uppercase()); }
Output:
HELLO WORLD
How to Convert a String to Lowercase in Rust?
Let’s explore how to convert a string to lowercase in Rust. Each uppercase character in a string is converted to lowercase.
Using the to_ascii_lowercase Function
The
to_ascii_lowercase
function returns the lowercase of an ASCII character in a string. For example ASCII characters such asA to Z
are converted toa to z
. Non-ASCII characters are not changed and return the same.Here is an example program
fn main() { let str = "Hello World"; println!(" {}", str.to_ascii_lowercase()); }
Output:
hello world
Using the to_lowercase Function
The
to_lowercase
function returns the lowercase of a string.Here is an example program
fn main() { let str = "HELLO WORLD"; println!(" {}", str.to_lowercase()); }
Output:
hello world
Conclusion
In this article, we’ve learned multiple methods with examples on how to,
- Convert a string into an uppercase string.
- Convert a string into a lowercase string.