Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a single Character type to uppercase?

Tags:

swift

All I want to do is convert a single Character to uppercase without the overhead of converting to a String and then calling .uppercased(). Is there any built-in way to do this, or a way for me to call the toupper() function from C without any bridging? I really don't think I should have to go out of my way for something so simple.

like image 302
Jared Avatar asked Apr 06 '17 17:04

Jared


People also ask

How do you convert character to uppercase?

ToUpper(Char) Converts the value of a Unicode character to its uppercase equivalent.

How do you convert a single character to uppercase in Python?

string capitalize() in Python Python String capitalize() method returns a copy of the original string and converts the first character of the string to a capital (uppercase) letter, while making all other characters in the string lowercase letters.

How do you convert letters to uppercase in C++?

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

How do you convert a lowercase character to uppercase in Java?

The java. lang. Character. toLowerCase(char ch) converts the character argument to lowercase using case mapping information from the UnicodeData file.


1 Answers

To call the C toupper() you need to get the Unicode code point of the Character. But Character has no method for getting its code point (a Character may consist of multiple code points), so you have to convert the Character into a String to obtain any of its code points.

So you really have to convert to String to get anywhere. Unless you store the character as a UnicodeScalar instead of a Character. In this case you can do this:

assert(unicodeScalar.isASCII) // toupper argument must be "representable as an unsigned char"
let uppercase = UnicodeScalar(toupper(CInt(unicodeScalar.value)))

But this isn't really more readable than simply using String:

let uppercase = Character(String(character).uppercased())
like image 50
emlai Avatar answered Oct 05 '22 04:10

emlai