将Unicode符号或其XML / HTML实体转换为Swift中的Unicode编号 [英] Convert Unicode symbol or its XML/HTML entities into its Unicode number in Swift
问题描述
String
或其XML / HTML实体,如何生成其Unicode编号?例如,如果给出字符串෴
,并且可以生成其HTML代码(෴ $ c $那么你怎么能生成它的Unicode号码( U + 0DF4
)?
我目前正在生成HTML实体通过使用 CFStringTransform
API并使用 kCFStringTransformToXMLHex
进行转换。但是这个unicode数字本身并没有一个转换。
解决方案 update: Xcode 9•Swift 4
扩展字符串{
var html2AttributedString:NSAttributedString? {
do {
return try NSAttributedString(data:Data(utf8),options:[.documentType:NSAttributedString.DocumentType.html,.characterEncoding:String.Encoding.utf8.rawValue],documentAttributes:nil)
} catch {
print(error)
return nil
}
}
var unicodes:[UInt32] {return unicodeScalars.map {$ 0.value }}
code $ <$ $ p
$ b Xcode 8•Swift 3
扩展字符串{
var html2AttributedString:NSAttributedString? {
do {
return try NSAttributedString(data:Data(utf8),options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:String.Encoding.utf8.rawValue],documentAttributes:nil)
} catch {
print(error)
return nil
}
}
var unicodes:[UInt32] {return unicodeScalars.map {$ 0.value}}
}
let str =< span>& euro;€< / span>。html2AttributedString?.string ??
print(str.unicodes)// [8364,8364]
Given either a unicode symbol as a String
or its XML/HTML entities, how could one generate its Unicode number? For example if you're given the string "෴"
, and you could generate its HTML code (෴
), how could you then generate its Unicode number (U+0DF4
)?
I am currently generating the HTML entities by using the CFStringTransform
API and using kCFStringTransformToXMLHex
for the transform. But there isn't a transform for the unicode number itself.
解决方案 update: Xcode 9 • Swift 4
extension String {
var html2AttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: Data(utf8), options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print(error)
return nil
}
}
var unicodes: [UInt32] { return unicodeScalars.map{$0.value} }
}
Xcode 8 • Swift 3
extension String {
var html2AttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: Data(utf8), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print(error)
return nil
}
}
var unicodes: [UInt32] { return unicodeScalars.map{$0.value} }
}
let str = "<span>€€</span>".html2AttributedString?.string ?? ""
print(str.unicodes) // [8364, 8364]
这篇关于将Unicode符号或其XML / HTML实体转换为Swift中的Unicode编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!