//程式碼
func compartStringByUnicode(string1 string1: String, string2: String, asc: Bool, index: Int)->Bool{
MyVariables.logger.debug("===============> index=\(index), asc=\(asc)")
let string1LengthEnough = string1.length > index
let string2LengthEnough = string2.length > index
if string1LengthEnough && string2LengthEnough {
let targetChar1 = string1.characters.map { String($0) }[index]
let targetChar2 = string2.characters.map { String($0) }[index]
for u1 in targetChar1.utf16 {
for u2 in targetChar2.utf16 {
if u1 == u2 {
return compartStringByUnicode(string1: string1, string2: string2, asc: asc, index: (index+1))
}else{
MyVariables.logger.debug("\(targetChar1) (\(u1), \(targetChar2) (\(u2)) ==> \(u1 < u2)")
if asc {
return u1 < u2
}else {
return u1 > u2
}
}
}
}
MyVariables.logger.debug("exception")
return false
}else{
if string1LengthEnough && !string2LengthEnough {
if asc {
MyVariables.logger.debug("string2不夠長 ==> false")
return false
}else {
MyVariables.logger.debug("string2不夠長 ==> true")
return true
}
}else{
if asc {
MyVariables.logger.debug("string1不夠長 ==> true")
return true
}else {
MyVariables.logger.debug("string1不夠長 ==> false")
return false
}
}
}
}
參考︰
http://jimmydeveloper.blogspot.tw/2015/01/swift.html
Unicode Lookup
UTF-8 Tool
NSString 與 Unicode
[C/C++] Unicode 與 UTF-8 互轉(C 語言實現)
unicode, ucs2, ucs4,utf-8,utf-16,utf-32關係和區別?
unicode是編碼標準,每個字母,每個漢字對應著一個碼。 比如中文的「我」,對應的unicode碼是6211。
unicode要實現,要存在文件系統中,需要對unicode碼進行存儲。
那麼存在文件系統中是存在62和11,還是11和62,還是其他形式,這個就是ucs2/ucs4/utf8/utf16/utf32要做的事情了。 他就是把unicode碼轉為文件系統中(內存中)存儲的編碼,可以認為是對unicode的實現方式。
由於unicode標準話有兩個組織,雖然它們對unicode編碼是一樣的(就是同一字母和漢字對應的編碼是一樣的,即,中文的「我」,對應的都是6211),但是存儲上有所區別。
這裡ucs2和utf16, ucs4和utf32是一樣的,只是不同組織對同一實現方式的不同名稱。
然後就剩下utf8/utf16/utf32的區別了。
utf8是變長編碼,顯然英文字母很少,它佔用兩個字節來代表一個字母實在是太浪費資源了,所以呢就可以用一個字節表示一個字母,用多個字節表示一個漢字。其中漢字的「我」,utf8的編碼是e6 88 91。
utf16和ucs2是一樣的,它用兩個字節代表一個字母或者漢字。它還涉及到small endian和big endian。
utf32和ucs4是一樣的,由於漢字博大精深,兩個字節都不可以裝下所有的漢字,於是就出現了4字節的編碼,也稱surrogate
How to convert an Int to Hex String in Swift
Hex to Decimal - Swift
// 我的unicode: U+6211
print("\u{6211}") // 我
// Hex to Decimal
UInt16(strtoul("6211", nil, 16)) // 25105
// 算法︰16^3*6 + 16^2*2 + 16^1*1 + 16^0*1 = 25105
// Decimal to Hex
NSString(format:"%X", 25105) // 6211
String(25105, radix: 16) // 6211
String(format:"%02X", 25105) // 6211
let myChar = "我"
for c in myChar.utf16 {
print("\(c)") // 25105
}
留言
張貼留言