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;

    }

    }



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


     

  • 相关阅读:
    HDU 2095 find your present (2) (异或)
    UESTC 486 Good Morning (水题+坑!)
    UVa 111 History Grading (简单DP,LIS或LCS)
    UVa 11292 Dragon of Loowater (水题,排序)
    HDU 1503 Advanced Fruits (LCS+DP+递归)
    UVa 10881 Piotr's Ants (等价变换)
    UVa 11178 Morley's Theorem (几何问题)
    HDU 1285 确定比赛名次(拓扑排序)
    .net Core的例子
    TCP与UDP的区别
  • 原文地址:https://www.cnblogs.com/xuefeng1982/p/1456121.html
Copyright © 2011-2022 走看看