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)