ASP.NET Core使用微软官方类库实现汉字转拼音

一、NuGet包

拼音:Install-Package PinYinConverterCore

简体-繁体互转:Install-Package TraditionalChineseToSimplifiedConverter

二、C#代码

    class Program
    {
     
        static void Main(string[] args)
        {

            string Name= "刘大大";

            Console.WriteLine($"{Name}\n全拼:{GetPinyin(Name)},\n首拼:{GetFirstPinyin(Name)},\n繁体字:{GetTraditional(Name)},\n简体字:{GetSimplified(GetTraditional(Name))}");


            Console.ReadKey();
        }

        

        ///  
        /// 汉字转化为拼音
        ///  
        /// 汉字 
        /// 全拼 
        public static string GetPinyin(string str)
        {
            string r = string.Empty;
            foreach (char obj in str)
            {
                try
                {
                    ChineseChar chineseChar = new ChineseChar(obj);
                    string t = chineseChar.Pinyins[0].ToString();
                    r += t.Substring(0, t.Length - 1);
                }
                catch
                {
                    r += obj.ToString();
                }
            }
            return r;
        }

        ///  
        /// 汉字转化为拼音首字母
        ///  
        /// 汉字 
        /// 首字母 
        public static string GetFirstPinyin(string str)
        {
            string r = string.Empty;
            foreach (char obj in str)
            {
                try
                {
                    ChineseChar chineseChar = new ChineseChar(obj);
                    string t = chineseChar.Pinyins[0].ToString();
                    r += t.Substring(0, 1);
                }
                catch
                {
                    r += obj.ToString();
                }
            }
            return r;
        }

        //  
        /// 简体转换为繁体
        ///  
        /// 简体字 
        /// 繁体字 
        public static string GetTraditional(string str)
        {
            string r = string.Empty;
            r = ChineseConverter.Convert(str, ChineseConversionDirection.SimplifiedToTraditional);
            return r;
        }
        ///  
        /// 繁体转换为简体
        ///  
        /// 繁体字 
        /// 简体字 
        public static string GetSimplified(string str)
        {
            string r = string.Empty;
            r = ChineseConverter.Convert(str, ChineseConversionDirection.TraditionalToSimplified);
            return r;
        }

        #endregion

    }
}
View Code

 运行结果

ASP.NET Core使用微软官方类库实现汉字转拼音_第1张图片

 

你可能感兴趣的:(ASP.NET Core使用微软官方类库实现汉字转拼音)