C#中文和UNICODE編碼轉換


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;
}

 

注:

1.這是前人的傑作,原著:http://www.cnblogs.com/scgw/archive/2009/07/02/1515915.html

2.稍后我會整理一下,最好能尋找一個更好的方法,因為這個一看就感覺到這方法的速度肯定快不起來啊,對於少量文本還行,多了就悲劇了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM