简体   繁体   English

Swift:用户输入的十六进制字符串到unicode字符

[英]Swift: User-inputted hex string to unicode character

I am having trouble converting a hex string that is inputted by the user (ie "1F436") to a unicode character I can work with. 我无法将用户输入的十六进制字符串(即“1F436”)转换为我可以使用的unicode字符。

From reading the Swift documentation, I learned how to print unicode characters using 'print(\\u{1F436})' and how to to figure out the decimal value of unicode characters in a string by using for-in loops. 通过阅读Swift文档,我学会了如何使用'print(\\ u {1F436})'来打印unicode字符,以及如何通过使用for-in循环来计算字符串中unicode字符的十进制值。

But how do I go about creating a unicode character variable from a string that contains its hexadecimal number? 但是,如何从包含十六进制数字的字符串创建unicode字符变量?

Very simple, just like this: 很简单,就像这样:

let inputText = "1F436"
let character = Int(inputText, radix: 16).map{ Character(UnicodeScalar($0)) }

character is an optional Character depending on whether the number was successfully parsed character是一个可选Character具体取决于数字是否已成功解析

The notation "\\u{1F436}" is only possible to use from the programmer, as it gets translated to the actual character at compile time 符号“\\ u {1F436}”只能在程序员中使用,因为它在编译时被转换为实际字符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM