2010年10月3日 星期日

【C#】Big5 to Unicode

//中文轉為UNICODE

string str = "中文";
string outStr = "";
if (!string.IsNullOrEmpty(str))
{
for (int i = 0; i < str.Length; i++)
{
//將中文轉為10進制整數,然後轉為16進制unicode
outStr += "\\u" + ((int)str[i]).ToString("x");
}
}

//UNICODE轉為中文

string str = "\\u963f\\u53ca";
string outStr = "";
if (!string.IsNullOrEmpty(str))
{
string[] strlist = str.Replace("\\", "").Split('u');
try
{
for (int i = 1; i < strlist.Length; i++)
{
//將unicode轉為10進制整數,然後轉為char中文
outStr += (char)int.Parse(strlist[i], System.Globalization.NumberStyles.HexNumber);
}
}
catch (FormatException ex)
{
outStr = ex.Message;
}
}

沒有留言: