PingYinHelper.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using Microsoft.International.Converters.PinYinConverter;
  2. using Microsoft.VisualStudio.TestTools.UnitTesting;
  3. using NUnit.Framework.Internal;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Text;
  7. namespace TEAMModelOS.SDK.Helper.Common.StringHelper
  8. {
  9. public static class PingYinHelper
  10. {
  11. /// <summary>
  12. /// 汉字转全拼
  13. /// </summary>
  14. /// <param name="strChinese"></param>
  15. /// <returns></returns>
  16. public static string ConvertToAllSpell(string strChinese)
  17. {
  18. try
  19. {
  20. if (strChinese.Length != 0)
  21. {
  22. StringBuilder fullSpell = new StringBuilder();
  23. for (int i = 0; i < strChinese.Length; i++)
  24. {
  25. var chr = strChinese[i];
  26. fullSpell.Append(GetSpell(chr));
  27. }
  28. return fullSpell.ToString().ToLower();
  29. }
  30. }
  31. catch (Exception e)
  32. {
  33. Console.WriteLine("全拼转化出错!" + e.Message);
  34. }
  35. return string.Empty;
  36. }
  37. /// <summary>
  38. /// 汉字转首字母
  39. /// </summary>
  40. /// <param name="strChinese"></param>
  41. /// <returns></returns>
  42. public static string GetFirstSpell(string strChinese)
  43. {
  44. //NPinyin.Pinyin.GetInitials(strChinese) 有Bug 洺无法识别
  45. //return NPinyin.Pinyin.GetInitials(strChinese);
  46. try
  47. {
  48. if (strChinese.Length != 0)
  49. {
  50. StringBuilder fullSpell = new StringBuilder();
  51. for (int i = 0; i < strChinese.Length; i++)
  52. {
  53. var chr = strChinese[i];
  54. fullSpell.Append(GetSpell(chr)[0]);
  55. }
  56. return fullSpell.ToString().ToLower();
  57. }
  58. }
  59. catch (Exception e)
  60. {
  61. Console.WriteLine("首字母转化出错!" + e.Message);
  62. }
  63. return string.Empty;
  64. }
  65. private static string GetSpell(char chr)
  66. {
  67. var coverchr = NPinyin.Pinyin.GetPinyin(chr);
  68. bool isChineses = ChineseChar.IsValidChar(coverchr[0]);
  69. if (isChineses)
  70. {
  71. ChineseChar chineseChar = new ChineseChar(coverchr[0]);
  72. foreach (string value in chineseChar.Pinyins)
  73. {
  74. if (!string.IsNullOrEmpty(value))
  75. {
  76. return value.Remove(value.Length - 1, 1);
  77. }
  78. }
  79. }
  80. return coverchr;
  81. }
  82. }
  83. }