實際上在C#中實現繁體和簡體的相互轉換還是比較容易的,一般有三種方法來實現,我這裡總結一下:
1,可以利用VB.NET中的StrConv方法來實現,由於C#中沒有提供這樣的方法,只好借用VB.NET裡的方法了:
需要先添加對Microsoft Visual Basic.net runtime.dll程式集的引用
如果這樣來實現轉換:
//繁體轉簡體
MessageBox.Show(Microsoft.VisualBasic.Strings.StrConv("張三",Microsoft.VisualBasic.VbStrConv.SimplifiedChinese,0));
//簡體轉繁體
MessageBox.Show(Microsoft.VisualBasic.Strings.StrConv("張三",Microsoft.VisualBasic.VbStrConv.TraditionalChinese,0));
2,單純的使用C#也可以實現,方法如下:
System.Text.Encoding gb2312=System.Text.Encoding.GetEncoding("gb2312");
System.Text.Encoding big5=System.Text.Encoding.GetEncoding("big5");
string s="這是一個漢字轉換測試";
byte[] bGb2312=gb2312.GetBytes(s);
byte[] bBig5=System.Text.Encoding.Convert(gb2312,big5,bGb2312);
string result=big5.GetString(bBig5);
3,也可以利用windows API來實現,定義一個用於轉換的靜態類ChineseStringConverter,通過LCMapString API來實現轉換
public static class ChineseStringConverter
{
internal const int LOCALE_SYSTEM_DEFAULT = 0x0800;
internal const int LCMAP_SIMPLIFIED_CHINESE = 0x02000000;
internal const int LCMAP_TRADITIONAL_CHINESE = 0x04000000;
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern int LCMapString(int Locale, int dwMapFlags, string lpSrcStr, int cchSrc, [Out] string lpDestStr, int cchDest);
public static string TraditionalToSimplified(string source)
{
String target = new String(' ', source.Length);
int ret = LCMapString(LOCALE_SYSTEM_DEFAULT, LCMAP_SIMPLIFIED_CHINESE, source, source.Length, target, source.Length);
return target;
}
public static string SimplifiedToTraditional(string source)
{
String target = new String(' ', source.Length);
int ret = LCMapString(LOCALE_SYSTEM_DEFAULT, LCMAP_TRADITIONAL_CHINESE, source, source.Length, target, source.Length);
return target;
}
}
我想到了這幾種方法,如果還有其他方法,請大家多多指教啊!