编程语言
首页 > 编程语言> > C#字符串Unicode转义序列编解码

C#字符串Unicode转义序列编解码

作者:互联网

C#字符串Unicode转义序列编解码

在开发过程中时常会遇到"\Uxxxx"格式表示的字符,实际上"xxxx"是字符的Unicode码的十六进制表示方式。这种表示称为"Unicode转义字符"。
例如"A"对应的Unicode码为65(十进制),转换后为"\U0041"。

以下C#封装的两个扩展函数,可以对Unicode字符串文本进行转义编码以及从转义序列解码。
1.解码:
        public static string UnescapeUnicode(this string str)  // 将unicode转义序列(\uxxxx)解码为字符串
        {
            return (System.Text.RegularExpressions.Regex.Unescape(str));
        }
2.编码:
        public static string EscapeUnicode(this string str)  // 将字符串编码为unicode转义序列(\uxxxx)
        {
            StringBuilder tmp = new StringBuilder();
            for (int i = 0; i < str.Length; i++)
            {
                ushort uxc = (ushort)str[i];
                tmp.Append(@"\u" + uxc.ToString("x4"));
            }
            return (tmp.ToString());
        }

参考:
https://blog.csdn.net/zcr_59186/

标签:tmp,编解码,Unicode,C#,转义序列,str,字符串,string
来源: https://www.cnblogs.com/netlog/p/15911016.html