/// <summary> /// Unicode编码(汉字转换为uxxx) /// </summary> /// <param name="str"></param> /// <returns></returns> public static string EnUnicode(string str) { StringBuilder strResult = new StringBuilder(); if (!string.IsNullOrEmpty(str)) { for (int i = 0; i < str.Length; i++) { strResult.Append("\u"); strResult.Append(((int)str[i]).ToString("x")); } } return strResult.ToString(); } /// <summary> /// Unicode解码(uxxxx转换为汉字) /// </summary> /// <param name="str"></param> /// <returns></returns> public static string DeUnicode(string str) { //最直接的方法Regex.Unescape(str); Regex reg = new Regex(@"(?i)\[uU]([0-9a-f]{4})"); return reg.Replace(str, delegate(Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); }); }
/// <summary> /// 汉字转换为Unicode编码(测试) /// </summary> /// <param name="str"></param> /// <returns></returns> public static string StringToUnicode(string str) { string result = ""; for (int i = 0; i < str.Length; i++) { result += "&#" + (int)(str.Substring(i, 1).ToCharArray()[0]) + ";"; } return result; }