目前手上有一个需要实现:将用户输入的姓名转换成汉语拼音。

使用枚举,既麻烦又易出错,发现有一个微软拼音转换工具类ChnCharInfo.dll,在此记录下:

首先需要引入此dll,

链接: http://pan.baidu.com/s/1hsa9Y40 密码: ijdi

写一个转换的Helper类:

public class ChineseToCharHelper
{
/// <summary>得到汉字拼音(Item1:全拼 2:首字母缩写 3:大写开头全拼)</summary>
/// <param name="chinese"></param>
/// <returns></returns>
public static Tuple<string, string, string> PinYinString(string chinese)
{
if (string.IsNullOrWhiteSpace(chinese)) return new Tuple<string, string, string>(string.Empty, string.Empty, string.Empty);
char[] ch = chinese.ToArray();
string allPinYin = string.Empty, abbPinYin = string.Empty, firstAllPinYin = string.Empty;
foreach (char c in ch)
{
if (ChineseChar.IsValidChar(c))
{
ChineseChar chineseChar = new ChineseChar(c);
ReadOnlyCollection<string> pinyin = chineseChar.Pinyins;
var duoyinList = pinyin.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Length >= ? x.Substring(, x.Length - ).ToLower() : string.Empty).ToList();
var dic = duoyinList.GroupBy(x => x).ToDictionary(x => x.Key, y => y.Count()).OrderByDescending(x => x.Value);
if (dic.Any())
{
if (dic.First().Value.Equals())
{
abbPinYin += pinyin[] != null && pinyin[].Length >=
? pinyin[].Substring(, )
: string.Empty;
allPinYin += pinyin[] != null && pinyin[].Length >
? pinyin[].Substring(, pinyin[].Length - )
: pinyin[] != null && pinyin[].Length.Equals()
? pinyin[].Substring(, )
: string.Empty;
var temp = pinyin[] != null && pinyin[].Length >
? pinyin[].Substring(, pinyin[].Length - )
: pinyin[] != null && pinyin[].Length.Equals()
? pinyin[].Substring(, )
: string.Empty;
firstAllPinYin += System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(temp.ToLower());
}
else
{
var value = dic.First().Key;
abbPinYin += value.Length >= ? value.Substring(, ) : string.Empty;
allPinYin += value;
firstAllPinYin += System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(value.ToLower());
}
}
}
else
{
abbPinYin += c.ToString();
allPinYin += c.ToString();
firstAllPinYin += System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(c.ToString().ToLower());
}
}
return new Tuple<string, string, string>(allPinYin.ToLower(), abbPinYin.ToLower(), firstAllPinYin);
}
}

直接调用就可以啦。

但是,组件存在BUG:

.net汉字转字母-LMLPHP

就像图中显示的样子,“汤” ,转换后的拼音是错误的。

其他的汉字转化吗,到还有发现。毕竟少数,特殊处理下就可以了,组件还是可用的。

05-08 08:32