zoukankan      html  css  js  c++  java
  • 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;

    }

    }



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


     

  • 相关阅读:
    Maven pom.xml中添加指定的中央仓库
    命令行远程链接MySQL
    A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war
    mvn deploy命令上传包
    保存好你的密码
    PuTTY免输密码自动登录Linux
    ActiveMQ无法启动
    linux控制台批量杀进程
    dubbo入门之微服务客户端服务端配置
    dubbo入门之helloWorld
  • 原文地址:https://www.cnblogs.com/xuefeng1982/p/1456121.html
Copyright © 2011-2022 走看看