ios開發之將中文轉換成字元值引用 (numeric character reference, NCR)

來源:互聯網
上載者:User

1,什麼是字元值引用

(1)字元值引用 (numeric character reference, NCR) 是在標記語言SGML以及派生的如HTML與XML中常見的一種逸出序列結構,用來表示Unicode的通用字元集 (UCS)中的單個字元. NCR可以表示在一個特定文檔中不能直接編碼的字元,而該標記語言閱讀器軟體把每個NCR當作一個字元來處理。
(2)我們可以將其理解為HTML、XML 等 SGML 類語言的逸出序列(escape sequence)。而不是一種編碼或轉碼。 

2,字元值引用的格式

以「&#x」開頭的後接十六進位數字。或者以「&#」開頭的後接十進位數字。


中国  //中國(16進位格式)
中国  //中國(10進位格式)

(不管哪種形式寫在html頁面中都會正常顯示出“中國”)

3,將一般字元串轉為字元值引用

由於Swift不提供原生的方法,那麼我們通過擴充String類來實現


extension String {
    //轉譯成字元值引用(NCR)
    func toHtmlEncodedString() -> String {
        var result:String = "";
        for scalar in self.utf16 {
            //將十進位轉成十六進位,不足4位前面補0
            let tem = String().stringByAppendingFormat("%04x",scalar)
            result += "&#x\(tem);";
        }
        return result
    }
}

使用:


let words = "歡迎來到 hangge.com"
print(words.toHtmlEncodedString())
//欢迎来到 hangge.com

4,將字元值引用轉位一般字元串 

同樣先擴充String類


extension String {
    init(htmlEncodedString: String) {
        do {
            let encodedData = htmlEncodedString.dataUsingEncoding(NSUTF8StringEncoding)!
            let attributedOptions : [String: AnyObject] = [
                NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
            ]
            let attributedString = try NSAttributedString(data: encodedData,
                options: attributedOptions, documentAttributes: nil)
            self.init(attributedString.string)
        } catch {
            fatalError("Unhandled error: \(error)")
        }
    }
}

使用:


let words = String(htmlEncodedString: "欢迎来到 hangge.com")
print(words)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.