Convert a char to upper case

2019-06-15 13:26发布

问题:

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.

回答1:

ToUppercase is an iterator, because there may be more that one uppercase version of some Unicode character because the uppercase version of the character may be composed of several codepoints, as delnan pointed in the comments. You can convert that to a Vector of characters:

c.to_uppercase().collect::<Vec<_>>();

Then, you should collect those characters into a string, as ker pointed.



回答2:

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.


标签: rust