PingYinHelper.cs 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. using Microsoft.International.Converters.PinYinConverter;
  2. using System;
  3. using System.Text;
  4. namespace TEAMModelOS.SDK
  5. {
  6. public static class PingYinHelper
  7. {
  8. /// <summary>
  9. /// 汉字转全拼
  10. /// </summary>
  11. /// <param name="strChinese"></param>
  12. /// <returns></returns>
  13. public static string ConvertToAllSpell(string strChinese)
  14. {
  15. try
  16. {
  17. if (strChinese.Length != 0)
  18. {
  19. StringBuilder fullSpell = new StringBuilder();
  20. for (int i = 0; i < strChinese.Length; i++)
  21. {
  22. var chr = strChinese[i];
  23. fullSpell.Append(GetSpell(chr));
  24. }
  25. return fullSpell.ToString().ToLower();
  26. }
  27. }
  28. catch (Exception e)
  29. {
  30. }
  31. return string.Empty;
  32. }
  33. /// <summary>
  34. /// 汉字转首字母
  35. /// </summary>
  36. /// <param name="strChinese"></param>
  37. /// <returns></returns>
  38. public static string GetFirstSpell(string strChinese)
  39. {
  40. //NPinyin.Pinyin.GetInitials(strChinese) 有Bug 洺无法识别
  41. //return NPinyin.Pinyin.GetInitials(strChinese);
  42. try
  43. {
  44. if (strChinese.Length != 0)
  45. {
  46. StringBuilder fullSpell = new StringBuilder();
  47. for (int i = 0; i < strChinese.Length; i++)
  48. {
  49. var chr = strChinese[i];
  50. fullSpell.Append(GetSpell(chr)[0]);
  51. }
  52. return fullSpell.ToString().ToLower();
  53. }
  54. }
  55. catch (Exception e)
  56. {
  57. }
  58. return string.Empty;
  59. }
  60. public static string GetSecondSpell(string strChinese)
  61. {
  62. //NPinyin.Pinyin.GetInitials(strChinese) 有Bug 洺无法识别
  63. //return NPinyin.Pinyin.GetInitials(strChinese);
  64. try
  65. {
  66. if (strChinese.Length != 0)
  67. {
  68. StringBuilder fullSpell = new StringBuilder();
  69. for (int i = 0; i < strChinese.Length; i++)
  70. {
  71. var chr = strChinese[i];
  72. var a = GetSpell(chr);
  73. if (a.Length > 1)
  74. {
  75. fullSpell.Append(a[1]);
  76. }
  77. else {
  78. fullSpell.Append(a[0]);
  79. }
  80. }
  81. return fullSpell.ToString().ToLower();
  82. }
  83. }
  84. catch (Exception e)
  85. {
  86. }
  87. return string.Empty;
  88. }
  89. public static string GetSpell(char chr)
  90. {
  91. var coverchr = NPinyin.Pinyin.GetPinyin(chr);
  92. bool isChineses = ChineseChar.IsValidChar(coverchr[0]);
  93. if (isChineses)
  94. {
  95. ChineseChar chineseChar = new ChineseChar(coverchr[0]);
  96. foreach (string value in chineseChar.Pinyins)
  97. {
  98. if (!string.IsNullOrEmpty(value))
  99. {
  100. return value.Remove(value.Length - 1, 1);
  101. }
  102. }
  103. }
  104. return coverchr;
  105. }
  106. }
  107. }