Is there a way to create a String from utf16 array in swift?

前端 未结 2 1359
予麋鹿
予麋鹿 2020-11-27 22:15

We know that String.utf16 provides the codeunits or String.unicodeScalars provides the scalars.

If we manipulate the codeunits and unicodeScales by removing some ele

相关标签:
2条回答
  • 2020-11-27 23:02

    Here it is.

    extension String {
        static func fromUTF16Chars(utf16s:UInt16[]) -> String {
            var str = ""
            for var i = 0; i < utf16s.count; i++ {
                let hi = Int(utf16s[i])
                switch hi {
                case 0xD800...0xDBFF:
                    let lo = Int(utf16s[++i])
                    let us = 0x10000
                        + (hi - 0xD800)*0x400 + (lo - 0xDC00)
                    str += Character(UnicodeScalar(us))
                default:
                    str += Character(UnicodeScalar(hi))
                }
            }
            return str
        }
    }
    
    let str = "aαあ                                                                    
    0 讨论(0)
  • 2020-11-27 23:14

    Update for Swift 2.1:

    You can create a String from an array of UTF-16 characters with the

    public init(utf16CodeUnits: UnsafePointer<unichar>, count: Int)
    

    initializer. Example:

    let str = "H€llo                                                                     
    0 讨论(0)
提交回复
热议问题