C#中文和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轉為中文(最直接的方法Regex.Unescape(input);)

string str = "\\u4e2d\\u6587";
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;
}
}

posted @ 2009-07-02 23:28  scgw  阅读(5777)  评论(4编辑  收藏  举报