您的位置:首页 > 编程语言 > C#

C# 中英文与Unicode之间的相互装换

2016-04-23 16:01 591 查看
/// <summary>
/// unicode转中文(符合js规则的)
/// </summary>
/// <returns></returns>
public string unicode_js_1(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
/// </summary>
/// <returns></returns>
public string unicode_0(string str)
{
string outStr = "";
if (!string.IsNullOrEmpty(str))
{
for (int i = 0; i < str.Length; i++)
{
String ss = ((int)str[i]).ToString("x");
if (ss.Length != 4)
{
for (int jj = 0; jj <= 4 - ss.Length; jj++)
{
ss = "0" + ss;
}

}
outStr += "\\u" + ss;
}
}
return outStr;
}


sim900

using System.Text.RegularExpressions;


/// <summary>
/// unicode转中文(符合js规则的)
/// </summary>
/// <returns></returns>
public string unicode_js_1(string str)
{
String ss = "";
//List<String> list = new List<string>();
int num = str.Length / 4;
for (int i = 0; i < num; i++ )
{
ss = ss + "\\u" + str.Substring(i * 4, 4);
}

str = ss;

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+"//"+ss;
}

/// 中英文转unicode
/// </summary>
/// <returns></returns>
public string unicode_0(string str)
{
string outStr = "";
if (!string.IsNullOrEmpty(str))
{
for (int i = 0; i < str.Length; i++)
{
String ss = ((int)str[i]).ToString("x");
if (ss.Length != 4)
{
for (int jj = 0; jj <= 4 - ss.Length; jj++)
{
ss = "0" + ss;
}

}
outStr += "\\u" + ss;
}
}
outStr = outStr.Replace("\\u", "");
return outStr;
}


/*
String str = "";

if (textBox1.Text == null)
{
return;

}

str = textBox1.Text.ToString();

byte[] data = {0x1A};

char c = (char)data[0];

int i = data[0];

MessageBox.Show("" + c, i+"");
*/

//SerialPort com = new SerialPort();
//com.BaudRate = 115200;
//com.PortName = "COM1";
//com.DataBits = 8;
//com.Open();//打开串口

//com.Write(data);
//com.Write(data,0,1);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: