2010年2月25日 星期四

轉貼 C# 與 unicode 互換

在 c# 將 字串 轉換為 unicode 字串(\u....\u....)




/**
* @name StringToUnicode
*
* String To Unicode
*
*
* @param srcText [in] - the table name
*
*
*/
private string StringToUnicode(string srcText)
{
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;
}




將 unicode 字串轉回 字串



/**
* @name UnicodeToString
*
* Unicode To String
*
*
* @param srcText [in] - the table name
*
*
*/
private 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),NumberStyles.HexNumber).ToString());
bytes[0] = byte.Parse(int.Parse(str.Substring(2, 2),NumberStyles.HexNumber).ToString());
dst += Encoding.Unicode.GetString(bytes);
}
return dst;
}



轉貼自

C#字串与Unicode互相转换方法

1 則留言:

Cc 提到...

前兩碼 \u 只是一個識別符號