C# 获取简体繁体汉字首字母
程序员文章站
2022-07-14 10:30:33
...
需要 ChnCharInfo.dll。
代码如下:
using System;
using Microsoft.International.Converters.PinYinConverter;
namespace Empty
{
public class ChineseCharOp
{
/// <summary>
/// 获取字符串首字拼音首字母 用于好友列表排序
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GetTextFirstPinYin(string str)
{
if (string.IsNullOrEmpty(str))
{
return null;
}
char obj = str[0];
try
{
ChineseChar chineseChar = new ChineseChar(obj);
string t = chineseChar.Pinyins[0].ToString();
return t.Substring(0, 1);
}
catch
{
return null;
}
}
/// <summary>
/// 获取全拼音
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GetTextPinYin(string str)
{
if (string.IsNullOrEmpty(str))
{
return null;
}
string strTemp = "";
for (int i = 0; i < str.Length; i++)
{
char obj = str[i];
try
{
ChineseChar chineseChar = new ChineseChar(obj);
string t = chineseChar.Pinyins[0].ToString();
t = System.Text.RegularExpressions.Regex.Replace(t, @"\d", ""); // 正则表达 去掉拼音中带有的数字
strTemp += t;
strTemp += " ";
}
catch
{
// 是否显示特殊字符
if (true)
{
strTemp += obj;
strTemp += " ";
}
}
}
return strTemp;
}
}
class Program
{
static void Main(string[] args)
{
string[] arrStr = new string[]
{
"简体字","體-繁に体","b字母","#符号","に日本语",""
};
Console.WriteLine("******************************************************************");
foreach (var s in arrStr)
{
string strTemp = ChineseCharOp.GetTextPinYin(s);
Console.WriteLine("汉全字:{0}\n头字音:{1}\n", s, !string.IsNullOrEmpty(strTemp) ? strTemp : "IsEmptyOrNull");
}
Console.WriteLine("******************************************************************");
foreach (var s in arrStr)
{
string strTemp = ChineseCharOp.GetTextFirstPinYin(s);
Console.WriteLine("汉全字:{0}\n全拼音:{1}\n", s, !string.IsNullOrEmpty(strTemp) ? strTemp : "IsEmptyOrNull");
}
Console.WriteLine("******************************************************************");
Console.ReadKey();
}
}
}
运行结果: