asp.net C#把Unicode编码转换为汉字,支持非Unicode编码字符串混合
从网上找的Unicode编码转换为汉字方法都是只能转换Unicode编码的字符串,但是有时会需要用到Unicode编码的汉字和其他字符串混用,所以才有了如下方法,很简单不多说了,直接看代码吧。。
/// <summary> /// 将Unicode编码转换为汉字,支持英文数字等字符串和Unicode编码字符串混合 /// </summary> /// <param name="str">含有Unicode编码字符串</param> /// <returns>汉字字符串</returns> public string UniToGB(string str) { string StrGb = ""; int i = 0; MatchCollection mc = Regex.Matches(str, @"\\u([\w]{2})([\w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase); byte[] bts = new byte[2]; if (mc.Count != 0) { foreach (Match m in mc) { bts[0] = (byte)int.Parse(m.Groups[2].Value, System.Globalization.NumberStyles.HexNumber); bts[1] = (byte)int.Parse(m.Groups[1].Value, System.Globalization.NumberStyles.HexNumber); string r = Encoding.Unicode.GetString(bts);//Unicode转为汉字 i++; if (i == 1) { StrGb = str.Replace(m.Groups[0].Value, r); } else { StrGb = StrGb.Replace(m.Groups[0].Value, r); } } return StrGb; } else { return str; } }