public static class WordHelper { /// <summary> /// 将汉字转换成拼音 /// </summary> /// <param name="str"></param> /// <param name="leftSeparate">间隔符(左)</param> /// <param name="rightSeparate">间隔符(右)</param> /// <param name="allPinYin">返回全部拼音</param> /// <param name="keepTone">保留音调</param> /// <returns></returns> public static string ToPinYin(string str, string leftSeparate, string rightSeparate, bool allPinYin, bool keepTone) { if (string.IsNullOrEmpty(str)) return ""; leftSeparate = leftSeparate ?? ""; rightSeparate = rightSeparate ?? ""; StringBuilder result = new StringBuilder(); for (int i = 0; i < str.Length; i++) { try { ChineseChar cc = new ChineseChar(str[i]); string py = ""; HashSet<string> used = new HashSet<string>(); for (int n = 0; n < (allPinYin ? cc.PinyinCount : 1); n++) { py = keepTone ? cc.Pinyins[n] : cc.Pinyins[n].Substring(0, cc.Pinyins[n].Length - 1); if (!used.Contains(py)) { result = result.Append(leftSeparate + py + rightSeparate); used.Add(py); } } } catch { result = result.Append(str[i]); } } return result.ToString(); } public static string ToPinYin(string str, string leftSeparate, string rightSeparate) { return ToPinYin(str, leftSeparate, rightSeparate, false, false); } /// <summary> /// 将汉字转换成拼音 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string ToPinYin(string str) { return ToPinYin(str, "", "", false, false); } /// <summary> /// 是否是汉字 /// </summary> /// <param name="c"></param> /// <returns></returns> public static bool IsChineseCharacter(char c) { try { ChineseChar cc = new ChineseChar(c); return true; } catch { } return false; } /// <summary> /// 获得笔画数 /// </summary> /// <param name="c"></param> /// <returns></returns> public static short ToStrokeNumber(char c) { short result = 0; try { ChineseChar cc = new ChineseChar(c); result = cc.StrokeNumber; } catch { } return result; } /// <summary> /// 简体转繁体 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string ToTraditional(string str) { return ChineseConverter.Convert(str, ChineseConversionDirection.SimplifiedToTraditional); } /// <summary> /// 繁体转简体 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string ToSimplified(string str) { return ChineseConverter.Convert(str, ChineseConversionDirection.TraditionalToSimplified); } }
using Microsoft.International.Converters.PinYinConverter; using Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter;