C#中漢字的繁體和簡體的相互轉換的兩個方法!

來源:互聯網
上載者:User

實際上在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;

}

}



我想到了這幾種方法,如果還有其他方法,請大家多多指教啊!

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.