Asp.Net将字符串转为&#区码位编码,或者将&#区码位编码字符串转为对应的字符串内容。
&#数字;这种编码其实就是将单个字符转为对应的区码位(数字),然后区码位前缀加上“&#”,后缀加上“;”组成,对于这种编码的字符串,浏览器会自动解析为对应的字符。
Asp.Net字符串和&#编码转换源代码和测试代码如下:
01 using System;
02 using System.Text.RegularExpressions;
03 public partial class purchase_property : System.Web.UI.Page
04 {
05 /// <summary>
06 /// Asp.Net将字符串转为16进制区码位&#编码
07 /// </summary>
08 /// <param name="s">要进行16进制区码位编码的字符串</param>
09 /// <returns>编码后的16进制区码位&#字符串</returns>
10 public string StringToUnicodeCodeBit(string s)
11 {
12 if (string.IsNullOrEmpty(s) || s.Trim() == "") return "";
13 string r = "";
14 for (int i = 0; i < s.Length; i++) r += "&#" + ((int)s[i]).ToString() + ";";
15 return r;
16 }
17 public string reMatchEvaluator(Match m)
18 {
19 return ((char)int.Parse(m.Groups[1].Value)).ToString();
20 }
21 /// <summary>
22 /// Asp.Net将16进制区码位&#编码转为对应的字符串
23 /// </summary>
24 /// <param name="s">16进制区码位编码的字符串</param>
25 /// <returns>16进制区码位编码的字符串对应的字符串</returns>
26 public string UnicodeCodeBitToString(string s)
27 {
28 if (string.IsNullOrEmpty(s) || s.Trim() == "") return "";
29 Regex rx = new Regex(@"&#(\d+);", RegexOptions.Compiled);
30 return rx.Replace(s, reMatchEvaluator);
31 }
32 protected void Page_Load(object sender, EventArgs e)
33 {
34 string s = "Asp.Net区码位字符串";
35 s = StringToUnicodeCodeBit(s);//转为&#编码
36 Response.Write(s);
37 Response.Write("\n");
38 s = UnicodeCodeBitToString(s);//&#编码转为字符串
39 Response.Write(s);
40 }
41 }
javascript版本可以参考下面:
01 function uncode(str) {//把&#编码转换成字符
02 return str.replace(/&#(x)?([^&]{1,5});?/g, function (a, b, c) {
03 return String.fromCharCode(parseInt(c, b ? 16 : 10));
04 });
05 }
06 function encode(str) {//把字符转换成&#编码
07 var a = [], i = 0;
08 for (; i < str.length; ) a[i] = str.charCodeAt(i++);
09 return "&#" + a.join(";&#") + ";";
10 }
更多信息请查看IT技术专栏