将Unicode符号或其XML / HTML实体转换为Swift中的Unicode编号 [英] Convert Unicode symbol or its XML/HTML entities into its Unicode number in Swift

查看:215
本文介绍了将Unicode符号或其XML / HTML实体转换为Swift中的Unicode编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个unicode符号为 String 或其XML / HTML实体,如何生成其Unicode编号?例如,如果给出字符串,并且可以生成其HTML代码(෴ 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 (&#3572;), 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>&euro;€</span>".html2AttributedString?.string ?? ""
print(str.unicodes)     // [8364, 8364]

这篇关于将Unicode符号或其XML / HTML实体转换为Swift中的Unicode编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆