简体   繁体   中英

Deferent result in Unicode to String in Swift

I am translating my String value to unicodeScalars with this down code, for example if I gave "A" as input I will get 65 as output, now that I know 65 is number of A , then I want give 65 to receive A again, but it gave e , I am sure I am mixing some topic together and also missing something, need some help for understanding why this is deferent and how can I use "\u{?????}" for returning my String, thanks

let string: String = "A"
let UInt32Value: UInt32 = string.unicodeScalars[string.startIndex].value
print(UInt32Value) // 65


let newString = "\u{65}"
print(newString) // e

ps: I know that there is official way of using unicodescalar to get the String back, but I am interested to "\u{?????}"

try to convert as follows

let ans =  String(UnicodeScalar(UInt8(65)))
print(ans)

I think the problem is, you are converting (A) string -> unicodescalar -> uint

and have to convert (65) uint -> unicodescalar -> string to get the original value

The \u{...} escape sequence uses hex:

Special characters can be included in string literals of both the single-line and multiline forms using the following escape sequences:

  • [...]
  • Unicode scalar ( \u{n} ), where n is a hexadecimal number that has one to eight digits

From the language reference .

So you need

"\u{41}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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