ASCII stands for American Standard Code for Information Interchange. It is a way of encoding a character set used for communication between computers. ASCII is the first among many encodings such as the UTF-8, ISO-8859-1, and so on.
A character is an ASCII character if it is a number between 0 and 9, an uppercase or lowercase letter from the English alphabet, or some special character. In Rust, we can use the is_ascii()
method to check if a character is within the ASCII range.
Rust provides two methods to convert an ASCII lowercase character to uppercase: to_ascii_uppercase()
and make_ascii_uppercase()
.
Note: These methods have no effect on characters that are ASCII numbers, ASCII special characters, and non-ASCII characters.
The code snippet below demonstrates how to use the to_ascii_uppercase()
method.
character.to_ascii_uppercase()
The following code snippet demonstrates how to use the make_ascii_uppercase()
method.
character.make_ascii_uppercase()
Both methods require one input parameter:
character
: This is the character we want to convert to uppercase.The to_ascii_uppercase()
method returns the uppercase ASCII equivalent of the input character. The above code snippet for to_ascii_uppercase()
will return the uppercase equivalent for character
.
The make_ascii_uppercase()
method converts the input character to its uppercase ASCII equivalent. The above code snippet for make_ascii_uppercase()
will convert the character
to its uppercase equivalent.
Let’s look at a few examples that use the above two methods to convert characters to uppercase in Rust.
fn main(){// Create characterslet char1 = 't';let char2 = '❤';let char3 = '!';// use to_ascii_uppercase() to convert to uppercaseprintln!("{} uppercase is {}", char1, char1.to_ascii_uppercase());println!("{} uppercase is {}", char2, char2.to_ascii_uppercase());println!("{} uppercase is {}", char3, char3.to_ascii_uppercase());// Create characterslet mut char4 = 'a';let mut char5 = '❤';let mut char6 = '!';// use make_ascii_uppercase() to convert to uppercasechar4.make_ascii_uppercase();char5.make_ascii_uppercase();char6.make_ascii_uppercase();// print uppercase charactersprintln!("{}", char4);println!("{}", char5);println!("{}", char6);}
char1
, is an ASCII letter character.to_ascii_uppercase()
to convert the above three characters to uppercase and print the result. The output shows that to_ascii_uppercase
only returns a different value for char1
.char4
is an ASCII letter character.make_ascii_uppercase()
to convert the new characters to uppercase.char4
, char5
, and char6
. The output shows that make_ascii_uppercase
only changed the value of char4
.