I saw that many places on the Internet use characters like /u4e2d/u56fd when transmitting Chinese, which are Unicode encoded characters, and I want to know what the specific content is, but it is not easy to see, so I want to decode this character set into normal characters. At first, I converted the encoding format through Encoding, and found that it didn't work, and I couldn't solve it normally, and then I searched for some similar decoding solutions on the Internet, which were feasible, but I found that it was a bit troublesome to write, and if I had batches of Unicode characters, I couldn't output them directly, and then I looked and looked at them, and finally, I found two methods of char classes: one is char. ConvertFromUtf32, the comment says: Convert the specified Unicode code bit to a UTF-16 encoded string, isn't this just decoding; Another is char. ConvertToUtf32, comment: This method is to convert UTF-16 encoded characters at specified positions in the string into Unicode code points, ha, in fact, it is to convert ordinary characters into Unicode character sets.
- /// <summary>
- /// 把Unicode解码为普通文字
- /// </summary>
- /// <param name="unicodeString">要解码的Unicode字符集</param>
- /// <returns>解码后的字符串</returns>
- public static string ConvertToGB(string unicodeString)
- {
- string[] strArray = unicodeString.Split(new string[] { @"\u" }, StringSplitOptions.None);
- string result = string.Empty;
- for (int i = 0; i < strArray.Length; i++)
- {
- if (strArray[i].Trim() == "" || strArray[i].Length < 2 || strArray.Length <= 1)
- {
- result += i == 0 ? strArray[i] : @"\u" + strArray[i];
- continue;
- }
- for (int j = strArray[i].Length > 4 ? 4 : strArray[i].Length; j >= 2; j--)
- {
- try
- {
- result += char.ConvertFromUtf32(Convert.ToInt32(strArray[i].Substring(0, j), 16)) + strArray[i].Substring(j);
- break;
- }
- catch
- {
- continue;
- }
- }
- }
- return result;
- }
- /// <summary>
- /// 把汉字字符转码为Unicode字符集
- /// </summary>
- /// <param name="strGB">要转码的字符</param>
- /// <returns>转码后的字符</returns>
- public static string ConvertToUnicode(string strGB)
- {
- char[] chs = strGB.ToCharArray();
- string result = string.Empty;
- foreach (char c in chs)
- {
- result += @"\u" + char.ConvertToUtf32(c.ToString(), 0).ToString("x");
- }
- return result;
- }
Copy code
|