項目以前使用的.net framework,能夠經過引用 Microsoft.International.Converters.PinYinConverter 類庫。來實現漢字轉拼音。
如今項目移植到.net core,以前的類庫已不能使用。spa
使用PinYinConverterCore包來實現漢字轉拼音。.net
Install-Package PinYinConverterCore
dotnet add package PinYinConverterCore
using Microsoft.International.Converters.PinYinConverter; namespace test { class Program { static void Main(string[] args) { string str = "我AI你中國!123"; string result = string.Empty; foreach (char item in str) { try { ChineseChar cc = new ChineseChar(item); if (cc.Pinyins.Count > 0 && cc.Pinyins[0].Length > 0) { string temp = cc.Pinyins[0].ToString(); result += temp.Substring(0, temp.Length - 1); } } catch (Exception) { result += item.ToString(); } } Console.WriteLine(result);//"WOAINIZHONGGUO!123" } } }
using Microsoft.International.Converters.PinYinConverter; using System.Linq; namespace test { class Program { static void Main(string[] args) { Console.WriteLine( GetFirstChar("我愛你"));// "W" Console.WriteLine(GetFirstChar("WO愛你"));// "W" Console.WriteLine(GetFirstChar("#我愛你"));// "#" } public static char GetFirstChar(string name) { var c = name.First(); if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')) { return c; } else { try { ChineseChar cc = new ChineseChar(c); if (cc.Pinyins.Count > 0 && cc.Pinyins[0].Length > 0) { return cc.Pinyins[0][0]; } } catch (Exception ex) { return c; } return c; } } } }