首页 > 代码库 > .net汉字转字母
.net汉字转字母
目前手上有一个需要实现:将用户输入的姓名转换成汉语拼音。
使用枚举,既麻烦又易出错,发现有一个微软拼音转换工具类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 >= 1 ? x.Substring(0, x.Length - 1).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(1)) { abbPinYin += pinyin[0] != null && pinyin[0].Length >= 1 ? pinyin[0].Substring(0, 1) : string.Empty; allPinYin += pinyin[0] != null && pinyin[0].Length > 1 ? pinyin[0].Substring(0, pinyin[0].Length - 1) : pinyin[0] != null && pinyin[0].Length.Equals(1) ? pinyin[0].Substring(0, 1) : string.Empty; var temp = pinyin[0] != null && pinyin[0].Length > 1 ? pinyin[0].Substring(0, pinyin[0].Length - 1) : pinyin[0] != null && pinyin[0].Length.Equals(1) ? pinyin[0].Substring(0, 1) : string.Empty; firstAllPinYin += System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(temp.ToLower()); } else { var value =http://www.mamicode.com/ dic.First().Key; abbPinYin += value.Length >= 1 ? value.Substring(0, 1) : 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); } }
直接调用就可以啦。
.net汉字转字母
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。