ASP.NET Core使用微软官方类库实现汉字转拼音

2021-03-06 09:26

阅读:686

标签:har   stat   官方   code   汉字   ram   color   字母   sim   

一、NuGet包

拼音:Install-Package PinYinConverterCore

简体-繁体互转:Install-Package TraditionalChineseToSimplifiedConverter

二、C#代码

class Program
 {
  
  static void Main(string[] args)
  {

   string Name= "刘大大";

   Console.WriteLine($"{Name}\n全拼:{GetPinyin(Name)},\n首拼:{GetFirstPinyin(Name)},\n繁体字:{GetTraditional(Name)},\n简体字:{GetSimplified(GetTraditional(Name))}");


   Console.ReadKey();
  }

  

  ///  
  /// 汉字转化为拼音
  ///  
  /// 汉字 
  /// 全拼 
  public static string GetPinyin(string str)
  {
   string r = string.Empty;
   foreach (char obj in str)
   {
    try
    {
     ChineseChar chineseChar = new ChineseChar(obj);
     string t = chineseChar.Pinyins[0].ToString();
     r += t.Substring(0, t.Length - 1);
    }
    catch
    {
     r += obj.ToString();
    }
   }
   return r;
  }

  ///  
  /// 汉字转化为拼音首字母
  ///  
  /// 汉字 
  /// 首字母 
  public static string GetFirstPinyin(string str)
  {
   string r = string.Empty;
   foreach (char obj in str)
   {
    try
    {
     ChineseChar chineseChar = new ChineseChar(obj);
     string t = chineseChar.Pinyins[0].ToString();
     r += t.Substring(0, 1);
    }
    catch
    {
     r += obj.ToString();
    }
   }
   return r;
  }

  // 
  /// 简体转换为繁体
  ///  
  /// 简体字 
  /// 繁体字 
  public static string GetTraditional(string str)
  {
   string r = string.Empty;
   r = ChineseConverter.Convert(str, ChineseConversionDirection.SimplifiedToTraditional);
   return r;
  }
  ///  
  /// 繁体转换为简体
  ///  
  /// 繁体字 
  /// 简体字 
  public static string GetSimplified(string str)
  {
   string r = string.Empty;
   r = ChineseConverter.Convert(str, ChineseConversionDirection.TraditionalToSimplified);
   return r;
  }

  #endregion

 }
}

 

ASP.NET Core使用微软官方类库实现汉字转拼音

标签:har   stat   官方   code   汉字   ram   color   字母   sim   

原文地址:https://www.cnblogs.com/dj1232090/p/12897969.html


评论


亲,登录后才可以留言!