结合多个unicode字符

时间:2016-01-07 11:14:14

标签: string swift unicode

我想组合多个unicode代码点,使用swift语言打印一个字符


    let str:String = "\u{0C95}\u{0CBE}"
    let combinedCahr:Character = Character(str)

这会打印ಕಾ

我的问题是:
我只想动态组合代码,如下所示。以下代码无法编译。


    let point1 = 0x0C95
    let point2 = 0x0CBE
    let str:String = "\u{(point1)}\u{(point2)}"
    let combinedCahr:Character = Character(str)
如何动态组合两个或多个unicode代码点来生成字符?

2 个答案:

答案 0 :(得分:3)

字符串"\u{0C95}\u{0CBE}"由Swift编译器解释,遗憾的是,您无法使用字符串插值(即运行时操作)来构建它。所以你需要寻找另一种方法。

String有一个初始化程序,它接受UTF16代码单元:

/// Returns an initialized `String` object that contains a
/// given number of characters from a given array of Unicode
/// characters.
public init(utf16CodeUnits: UnsafePointer<unichar>, count: Int)

如果您看到UnsafePointer类型为T的内容,则可以使用[T]调用该功能。由于初始化程序也需要计数,只需构建一个unichar的Swift数组,并将该数组及其计数传递给构造函数:

let point1: unichar = 0x0C95
let point2: unichar = 0x0CBE

let units = [point1, point2]
let str = String(utf16CodeUnits: units, count: units.count)
let combinedChar = Character(str)

答案 1 :(得分:2)

组合字符串将(扩展的)字形集合组合成单个字符, 所以这是一个替代解决方案:

let point1 = 0x0C95
let point2 = 0x0CBE

let s1 = String(UnicodeScalar(point1)) // "ಕ"
let s2 = String(UnicodeScalar(point2)) // "ಾ"

let combined = Character(s1 + s2) // "ಕಾ"

另一个例子(代码点在&#34;基本多语言平面&#34之外):

let point1 = 0x1F1E9
let point2 = 0x1F1EA

let s1 = String(UnicodeScalar(point1)) // ""
let s2 = String(UnicodeScalar(point2)) // ""

let combined = Character(s1 + s2) // ""