/// <summary> /// 将指定中文字符串转换为拼音形式 /// </summary> /// <param name="chs">要转换的中文字符串</param> /// <param name="separator">连接拼音之间的分隔符</param> /// <param name="initialCap">指定是否将首字母大写</param> /// <returns>包含中文字符串的拼音的字符串</returns> public static string CHSToPhoneticize(string chs, string separator, bool initialCap) { if (string.IsNullOrEmpty(chs)) return ""; if (string.IsNullOrEmpty(separator)) separator = ""; // 例外词组 chs = CHSPhraseSpecial.Cast<DictionaryEntry>().Aggregate(chs, (current, de) => current.Replace(de.Key.ToString(), String.Format("\r\r\r{0}\r\r\r", de.Value.ToString().Replace(" ", separator)))); string returnstr = ""; bool b = false, d = false; char[] nowchar = chs.ToCharArray(); CultureInfo ci = Thread.CurrentThread.CurrentCulture; TextInfo ti = ci.TextInfo; for (int j = 0; j < nowchar.Length; j++) { byte[] array = Encoding.Default.GetBytes(nowchar[j].ToString()); string s = nowchar[j].ToString(); if (array.Length == 1) { b = true; returnstr += s; } else { int i1 = (array[0]); int i2 = (array[1]); int chrasc = i1 * 256 + i2 - 65536; for (int i = (_phoneticizeValues.Length - 1); i >= 0; i--) { if (_phoneticizeValues[i] <= chrasc) { d = true; s = _phoneticizeNames[i]; if (initialCap) s = ti.ToTitleCase(s); if (returnstr == "" || b) returnstr += s; else returnstr += separator + s; break; } d = false; } if (d == false) returnstr += s; b = false; } } returnstr = returnstr.Replace("\r\r\r", separator); return returnstr; }
/// <summary> /// 将指定中文字符串转换为拼音形式 /// </summary> /// <param name="chs">要转换的中文字符串</param> /// <param name="separator">连接拼音之间的分隔符</param> /// <param name="initialCap">指定是否将首字母大写</param> /// <returns></returns> public static string CHSToPinyin(string chs, string separator, bool initialCap) { if (string.IsNullOrEmpty(chs)) { return(""); } if (string.IsNullOrEmpty(separator)) { separator = ""; } chs = CHSPhraseSpecial.Cast <DictionaryEntry>().Aggregate <DictionaryEntry, string>(chs, (current, de) => current.Replace(de.Key.ToString(), string.Format("\r\r\r{0}\r\r\r", de.Value.ToString().Replace(" ", separator)))); string str = ""; bool flag = false; bool flag2 = false; char[] chArray = chs.ToCharArray(); TextInfo textInfo = Thread.CurrentThread.CurrentCulture.TextInfo; for (int i = 0; i < chArray.Length; i++) { byte[] bytes = Encoding.Default.GetBytes(chArray[i].ToString()); string str2 = chArray[i].ToString(); if (bytes.Length == 1) { flag = true; str = str + str2; continue; } int num2 = bytes[0]; int num3 = bytes[1]; int num4 = ((num2 * 0x100) + num3) - 0x10000; for (int j = PinyinValues.Length - 1; j >= 0; j--) { if (PinyinValues[j] <= num4) { flag2 = true; str2 = PinyinNames[j]; if (initialCap) { str2 = textInfo.ToTitleCase(str2); } if ((str == "") || flag) { str = str + str2; } else { str = str + separator + str2; } break; } flag2 = false; } if (!flag2) { str = str + str2; } flag = false; } return(str.Replace("\r\r\r", separator)); }