C# Unicode (\uxxxx) 和 中文 變數互轉
C# Unicode (\uxxxx) 和 中文 變數互轉
資料來源:http://trufflepenne.blogspot.com/2013/03/cunicode.html
GOOGLE: C# \uXXXX
https://www.cnblogs.com/netlog/p/15911016.html C#字符串Unicode转义序列编解码
https://docs.microsoft.com/zh-tw/dotnet/api/system.text.regularexpressions.regex.unescape?view=net-6.0
https://www.cnblogs.com/sntetwt/p/11218087.html [C# 將非英數字轉成UNICODE]
Code
//--- //單純只針對非英數字(中文字)部分轉Unicode編碼 static string StringToUnicode(string text) { //https://www.cnblogs.com/sntetwt/p/11218087.html string result = ""; for (int i = 0; i < text.Length; i++) { if ((int)text[i] > 32 && (int)text[i] < 127) { result += text[i].ToString(); } else result += string.Format("\\u{0:x4}", (int)text[i]); } return result; } //---單純只針對非英數字(中文字)部分轉Unicode編碼
/*使用範例 Console.WriteLine(StringToUnicode("廖")); //UTF-8 轉中文 String result00 = string.Format(@"\u"+"{0:x4}", 24278); String result01 = "\u5ed6"; String StrBuf00 = UnescapeUnicode(result00+"jashliao中文1234"); String StrBuf01 = StringToUnicode(result01); Console.Write(UnicodeToString(StrBuf01)); */ static string StringToUnicode(string srcText) { //http://trufflepenne.blogspot.com/2013/03/cunicode.html string dst = ""; char[] src = srcText.ToCharArray(); for (int i = 0; i < src.Length; i++) { byte[] bytes = Encoding.Unicode.GetBytes(src[i].ToString()); string str = @"\u" + bytes[1].ToString("X2") + bytes[0].ToString("X2"); dst += str; } return dst; } static string UnicodeToString(string srcText) { //http://trufflepenne.blogspot.com/2013/03/cunicode.html string dst = ""; string src = srcText; int len = srcText.Length / 6; for (int i = 0; i <= len - 1; i++) { string str = ""; str = src.Substring(0, 6).Substring(2); src = src.Substring(6); byte[] bytes = new byte[2]; bytes[1] = byte.Parse(int.Parse(str.Substring(0, 2), System.Globalization.NumberStyles.HexNumber).ToString()); bytes[0] = byte.Parse(int.Parse(str.Substring(2, 2), System.Globalization.NumberStyles.HexNumber).ToString()); dst += Encoding.Unicode.GetString(bytes); } return dst; } public static string UnescapeUnicode(string str) // 将unicode转义序列(\uxxxx)解码为字符串 { //GOOGLE: C# \uXXXX //https://www.cnblogs.com/netlog/p/15911016.html C#字符串Unicode转义序列编解码 //https://docs.microsoft.com/zh-tw/dotnet/api/system.text.regularexpressions.regex.unescape?view=net-6.0 return (System.Text.RegularExpressions.Regex.Unescape(str)); }
2 thoughts on “C# Unicode (\uxxxx) 和 中文 變數互轉”
C# UNICODE (\UXXXX) 和 中文 變數互轉
C#字符串Unicode轉義序列編解碼
將unicode轉義(轉換)序列(\uxxxx)解碼為字符串(字串)
通過替換爲轉義碼來轉義最小的字符集(\、*、+、?、|、{、[、(、)、^、$、.、# 和空白)。這將指示正則表達式引擎按原義解釋這些字符而不是解釋爲元字符。