一、事故現場
項目之前使用的.net framework,可以通過引用 Microsoft.International.Converters.PinYinConverter 類庫。來實現漢字轉拼音。
現在項目移植到.net core,之前的類庫已不能使用。
二、解決方法
使用PinYinConverterCore包來實現漢字轉拼音。
1、安裝方法
- Nuget
Install-Package PinYinConverterCore
- .NET CLI
dotnet add package PinYinConverterCore
2、代碼示例
#中文轉拼音
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;
}
}
}
}