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/