C# 將中文字轉換成unicode格式 / unicode格式轉換中文字[應用在中文寫入/讀取 SQLITE]
C# 將中文字轉換成unicode格式 / unicode格式轉換中文字[應用在中文寫入/讀取 SQLITE](中文 <-> \u)
資料來源: https://blog.csdn.net/u011511086/article/details/72865006/
Code
/// <summary> /// 字串轉Unicode 直接Byte的方式,單位元組操作 /// </summary> /// <param name="source">源字串</param> /// <returns>Unicode編碼後的字串</returns> public static string StringToUnicode(string source) { var bytes = Encoding.Unicode.GetBytes(source); var stringBuilder = new StringBuilder(); for (var i = 0; i < bytes.Length; i += 2) { stringBuilder.AppendFormat("\\u{0:x2}{1:x2}", bytes[i + 1], bytes[i]); } return stringBuilder.ToString(); } /// <summary> /// 字串轉為UniCode碼字串 通過Char的方式,一個Char為兩個位元組 /// </summary> /// <param name="s"></param> /// <returns></returns> public static string StringToUnicode(string s) { char[] charbuffers = s.ToCharArray(); byte[] buffer; StringBuilder sb = new StringBuilder(); for (int i = 0; i < charbuffers.Length; i++) { buffer = System.Text.Encoding.Unicode.GetBytes(charbuffers[i].ToString()); sb.Append(String.Format("\\u{0:X2}{1:X2}", buffer[1], buffer[0])); } return sb.ToString(); } /// <summary> /// Unicode字串轉為正常字串 例如:1的Unicode為 \u0031 /// </summary> /// <param name="srcText"></param> /// <returns></returns> public static string UnicodeToString(string srcText) { 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; }
One thought on “C# 將中文字轉換成unicode格式 / unicode格式轉換中文字[應用在中文寫入/讀取 SQLITE]”
StrOutput=System.Text.RegularExpressions.Regex.Unescape(StrOutput);// \u -> 中文