c#中文转unicode字符示例分享
程序员文章站
2024-02-18 08:00:10
复制代码 代码如下://可以包括其他字符 public string uncode(string str) { string outstr = ""; regex reg...
复制代码 代码如下:
//可以包括其他字符
public string uncode(string str)
{
string outstr = "";
regex reg = new regex(@"(?i)//u([0-9a-f]{4})");
outstr = reg.replace(str, delegate(match m1)
{
return ((char)convert.toint32(m1.groups[1].value, 16)).tostring();
});
return outstr;
}
//中文转为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 = "//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;
}
}