码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2020-05-16 00:40:19      阅读:104      评论:0      收藏:0      [点我收藏+]

标签: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();
  }

  

  /// <summary> 
  /// 汉字转化为拼音
  /// </summary> 
  /// <param name="str">汉字</param> 
  /// <returns>全拼</returns> 
  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;
  }

  /// <summary> 
  /// 汉字转化为拼音首字母
  /// </summary> 
  /// <param name="str">汉字</param> 
  /// <returns>首字母</returns> 
  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;
  }

  // <summary> 
  /// 简体转换为繁体
  /// </summary> 
  /// <param name="str">简体字</param> 
  /// <returns>繁体字</returns> 
  public static string GetTraditional(string str)
  {
   string r = string.Empty;
   r = ChineseConverter.Convert(str, ChineseConversionDirection.SimplifiedToTraditional);
   return r;
  }
  /// <summary> 
  /// 繁体转换为简体
  /// </summary> 
  /// <param name="str">繁体字</param> 
  /// <returns>简体字</returns> 
  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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!