1, what is the character value reference
(1) Character value reference (numeric character reference, NCR) is an escape sequence structure commonly used in markup language SGML and derived, such as HTML and XML, to represent a single character in the universal Character set (UCS) of Unicode. NCR can represent characters that cannot be encoded directly in a particular document, and the markup language reader software treats each NCR as a single character.
(2) We can interpret it as an escape sequence (escape sequence) for SGML languages such as HTML and XML. Rather than a code or transcoding.
2, the character value refers to the format
The hexadecimal number that begins with the "& #x". or a decimal number that begins with "&#".
& #x4e2d;& #x56fd; China (16 in-system format)
& #20013;& #22269; China (10 in-system format)
(no matter which form is written in the HTML page will normally show "China")
3, convert a normal string to a character value reference
Since Swift does not provide native methods, we extend the string class to implement the
Extension String {
Translate to character value reference (NCR)
Func tohtmlencodedstring ()-> String {
var result:string = "";
For scalar in Self.utf16 {
Turn decimal to 16, less than 4 digits ahead of 0
Let tem = String (). Stringbyappendingformat ("%04x", scalar)
Result + = "& #x (TEM);";
}
return result
}
}
Use:
Let words = "Welcome to hangge.com"
Print (words.tohtmlencodedstring ())
& #x6b22;& #x8fce;& #x6765;& #x5230;& #x0020;& #x0068;& #x0061;& #x006e;& #x0067; & #x0067;& #x0065;& #x002e;& #x0063;& #x006f;& #x006d;
4, reference the character value to the normal string
Expand the String class first
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)")
}
}
}
Use:
Let words = String (htmlencodedstring: "& #x6b22;& #x8fce;& #x6765;& #x5230;& #x0020;& #x0068; & #x0061;& #x006e;& #x0067;& #x0067;& #x0065;& #x002e;& #x0063;& #x006f;& #x006d; ")
print (words)