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/


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM