文字轉拼音與簡寫
阿新 • • 發佈:2018-03-02
isnull mod gpo idc action () get regex substring
引用的插件為微軟的 Microsoft.International.Converters.PinYinConverter
在NuGet中查找 PinYinConverter
1 public class PingYinModel 2 { 3 public List<string> TotalPingYin = new List<string>(); 4 public List<string> FirstPingYin = new List<string>(); 5 } 6 7 public ActionResult About()8 { 9 //ViewBag.Message = "Your application description page."; 10 PingYinModel pingyins = GetTotalPingYin("銀行,(孢)"); 11 12 ViewBag.pinyins = "銀行,(孢) <br/>"; 13 ViewBag.pinyins += "全拼音:" + String.Join(",", pingyins.TotalPingYin) + "<br/>"; 14 ViewBag.pinyins += "首音:" + String.Join(",", pingyins.FirstPingYin); 15 return View(); 16 } 17 public static PingYinModel GetTotalPingYin(string str) 18 { 19 var chs = str.ToCharArray(); 20 //記錄每個漢字的全拼 21 Dictionary<int, List<string>> totalPingYins = new Dictionary<int, List<string>>(); 22 for (int i = 0; i < chs.Length; i++) 23 { 24 var pinyins = new List<string>(); 25 var ch = chs[i]; 26 //是否是有效的漢字 27 if (ChineseChar.IsValidChar(ch)) 28 { 29 ChineseChar cc = new ChineseChar(ch); 30 pinyins = cc.Pinyins.Where(p => !string.IsNullOrWhiteSpace(p)).ToList(); 31 } 32 else 33 { 34 pinyins.Add(ch.ToString()); 35 } 36 37 //去除聲調,轉小寫 38 pinyins = pinyins.ConvertAll(p => Regex.Replace(p, @"\d", "").ToLower()); 39 //去重 40 pinyins = pinyins.Where(p => !string.IsNullOrWhiteSpace(p)).Distinct().ToList(); 41 if (pinyins.Any()) 42 { 43 totalPingYins[i] = pinyins; 44 } 45 } 46 PingYinModel result = new PingYinModel(); 47 foreach (var pinyins in totalPingYins) 48 { 49 var items = pinyins.Value; 50 if (result.TotalPingYin.Count <= 0) 51 { 52 result.TotalPingYin = items; 53 result.FirstPingYin = items.ConvertAll(p => p.Substring(0, 1)).Distinct().ToList(); 54 } 55 else 56 { 57 //全拼循環匹配 58 var newTotalPingYins = new List<string>(); 59 foreach (var totalPingYin in result.TotalPingYin) 60 { 61 newTotalPingYins.AddRange(items.Select(item => totalPingYin + item)); 62 } 63 newTotalPingYins = newTotalPingYins.Distinct().ToList(); 64 result.TotalPingYin = newTotalPingYins; 65 66 //首字母循環匹配 67 var newFirstPingYins = new List<string>(); 68 foreach (var firstPingYin in result.FirstPingYin) 69 { 70 newFirstPingYins.AddRange(items.Select(item => firstPingYin + item.Substring(0, 1))); 71 } 72 newFirstPingYins = newFirstPingYins.Distinct().ToList(); 73 result.FirstPingYin = newFirstPingYins; 74 } 75 } 76 return result; 77 }
效果圖
文字轉拼音與簡寫