Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a char to upper case

Tags:

rust

I have a variable which contains a single char. I want to convert this char to upper case. However, the to_uppercase function returns a rustc_unicode::char::ToUppercase struct instead of a char.

like image 256
Moebius Avatar asked Feb 16 '16 12:02

Moebius


People also ask

How do you convert lowercase characters to uppercase?

Changing between lowercase and uppercase on a smartphone or tablet. On smartphones and tablets, there is no Caps Lock key or Shift key. To uppercase (capitalize) a letter on these devices, press the up arrow on the on-screen keyboard and then the letter you want to be capitalized.

Which function converts a character to upper case?

The toupper() function is used to convert lowercase alphabet to uppercase. i.e. If the character passed is a lowercase alphabet then the toupper() function converts a lowercase alphabet to an uppercase alphabet. It is defined in the ctype. h header file.

How do you make a character upper case in Java?

Java String toUpperCase() Method The toUpperCase() method converts a string to upper case letters.

How do you make a char uppercase in C++?

The toupper() function in C++ converts a given character to uppercase. It is defined in the cctype header file.


1 Answers

Explanation

ToUppercase is an Iterator, that may yield more than one char. This is necessary, because some Unicode characters consist of multiple "Unicode Scalar Values" (which a Rust char represents).

A nice example are the so called ligatures. Try this for example (on playground):

let fi_upper: Vec<_> = 'fi'.to_uppercase().collect();
println!("{:?}", fi_upper);   // prints: ['F', 'I']

The 'fi' ligature is a single character whose uppercase version consists of two letters/characters.


Solution

There are multiple possibilities how to deal with that:

  1. Work on &str: if your data is actually in string form, use str::to_uppercase which returns a String which is easier to work with.
  2. Use ASCII methods: if you are sure that your data is ASCII only and/or you don't care about unicode symbols you can use std::ascii::AsciiExt::to_ascii_uppercase which returns just a char. But it only changes the letters 'a' to 'z' and ignores all other characters!
  3. Deal with it manually: Collect into a String or Vec like in the example above.
like image 173
Lukas Kalbertodt Avatar answered Sep 18 '22 15:09

Lukas Kalbertodt