随笔 - 139  文章 - 0  评论 - 421  阅读 - 17万

C#中汉字的繁体和简体的相互转换的两个方法!

实际上在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;

}

}



我想到了这几种方法,如果还有其他方法,请大家多多指教啊!


 

posted on   周雪峰  阅读(2041)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
< 2009年5月 >
26 27 28 29 30 1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31 1 2 3 4 5 6

点击右上角即可分享
微信分享提示