张赐荣——一位视障程序员。
赐荣小站: www.prc.cx

張賜榮

张赐荣的技术博客

博客园 首页 新随笔 联系 订阅 管理

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/

posted on 2022-02-18 19:11  张赐荣  阅读(2242)  评论(0编辑  收藏  举报

感谢访问张赐荣的技术分享博客!
博客地址:https://cnblogs.com/netlog/
知乎主页:https://www.zhihu.com/people/tzujung-chang
个人网站:https://prc.cx/