C# 汉字转化拼音的简单实例代码
首先引入chncharinfo.dll 第3方的一个库
代码:
btn_chinchar_click事件:
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;
}
}
运用结果: