C# 汉字转化拼音的简单实例代码
首先引入ChnCharInfo.dll 第3方的一个库
代码:
private void btn_chinChar_Click(object sender, EventArgs e)
{
ChineseChar cr =null;
string str = "", txtString = txt_string.Text.Trim();
if (!string.IsNullOrEmpty(txtString))
{
foreach (var item in cr.GetChineseSpellings(txtString))
{
str += item + "-";
}
}
MessageBox.Show(str);
}
扩展方法:
public static class ChineseCharacters
{
public static ICollection<string> GetChineseSpellings(this ChineseChar chinChar ,string value)
{
List<string> list;
int i,start;
char c;
if (string.IsNullOrEmpty(value))return null;
start = 0;
list = new List<string>();
for (i = 0; i < value.Length; ++i)
{
c = value[i];
if (ChineseChar.IsValidChar(c))
{
if (i > start)
{
list.Add(value.Substring(start, i - start));
}
chinChar = new ChineseChar(c);
list.Add(chinChar.Pinyins.First().Substring(0, chinChar.Pinyins.First().Length - 1).ToLower());
start = i + 1;
}
}
if (i > start)
{
list.Add(value.Substring(start, i - start));
}
return list;
}
}
运用结果: