微软自认为很完美!
ChnCharInfo.dll ,这个是微软官方发布的专门用于处理汉字的工具包,汉字转拼音是完全没问题的。把它放到项目目录的bin文件夹,在项目中右键“引用”——浏览,找到该文件,点确定即可。为确保引用到项目中,最好在项目中的“引用”项看到它后,右键属性,将“复制本地”选为true。
创建一个PinYinHelper类,引入Microsoft.International.Converters.PinYinConverter命名空间。代码:
public static class PinYinHelper {
public static string ToPinYin(string txt)
{
txt = txt.Trim();
byte[] arr = new byte[2]; //每个汉字为2字节
StringBuilder result = new StringBuilder();//使用StringBuilder优化字符串连接
char[] arrChar = txt.ToCharArray();
foreach (char c in arrChar)
{
arr = System.Text.Encoding.Default.GetBytes(c.ToString());//根据系统默认编码得到字节码
if (arr.Length == 1)//如果只有1字节说明该字符不是汉字 {
result.Append(c.ToString());
continue;
}
ChineseChar chineseChar = new ChineseChar(c);
result.Append(chineseChar.Pinyins[0].Substring(0, chineseChar.Pinyins[0].Length - 1).ToLower());
result.Append(" ");
}
return result.ToString();
}
}