Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

ios - Convert Unicode symbol or its XML/HTML entities into its Unicode number in Swift

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

update: Xcode 11.4 ? Swift 5.2

extension String {
    var data: Data { .init(utf8) }
    var html2AttributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            print(error)
            return nil
        }
    }
    var html2String: String { html2AttributedString?.string ?? "" }
    var unicodes: [UInt32] { unicodeScalars.map(.value) }
}

let str = "<span>&euro;€</span>".html2String  // "€€"
str.unicodes                                  // [8364, 8364]


extension StringTransform {
    static let toUnicodeHex = Self("Hex/Unicode")
    static let toJavaHex = Self("Hex/Java")
    static let toPerlHex = Self("Hex/Perl")
}

extension String {
    var convertedToUnicodeHex: String { applyingTransform(.toUnicodeHex, reverse: false) ?? "" }
    var convertedToJavaHex: String { applyingTransform(.toJavaHex, reverse: false) ?? "" }
    var convertedToXMLHex: String { applyingTransform(.toXMLHex, reverse: false) ?? "" }
    var convertedToPerlHex: String { applyingTransform(.toPerlHex, reverse: false) ?? "" }
}

"?".convertedToUnicodeHex  // U+0DF4
"?".convertedToJavaHex     // u0DF4
"?".convertedToXMLHex      // &#xDF4;
"?".convertedToPerlHex     // x{DF4}
"?".unicodes               // [3572]
0x0DF4                      // 3572

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...