C# unity 中实现汉字转拼音

首先下载安装必要的库文件

C# unity 中实现汉字转拼音_第1张图片

安装后的地址

C:\Program Files (x86)\Microsoft Visual Studio International Pack\Simplified Chinese Pin-Yin Conversion Library

在文件夹下放入这几个库文件

C# unity 中实现汉字转拼音_第2张图片

会遇到unity中打包后,出现 Encoding.GetEncoding("GB2312")  把这两个文件复制放入到  libs 下就行了

C# unity 中实现汉字转拼音_第3张图片

using UnityEngine;
using System.Collections;
using System.Text;
using System;
using NPinyin;
using Microsoft.International.Converters.PinYinConverter;

public class PingYinHelper
{
    private static Encoding gb2312 = Encoding.GetEncoding("GB2312");

    /// 
    /// 汉字转全拼
    /// 
    /// 
    /// 
    public static string ChToAllPy(string strCh)
    {
        try
        {
            if (strCh.Length != 0)
            {
                StringBuilder strBuilder = new StringBuilder();
                for (int i = 0; i < strCh.Length; i++)
                {
                    var chr = strCh[i];
                    strBuilder.Append(GetSpell(chr));
                }

                return strBuilder.ToString().ToUpper();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("汉字转拼音错误 ex= " + e.Message);
        }

        return string.Empty;
    }

    /// 
    /// 汉字转首字母
    /// 
    /// 
    /// 
    public static string GetFirstSpell(string strCh)
    {
        try
        {
            if (strCh.Length != 0)
            {
                StringBuilder fullSpell = new StringBuilder();
                for (int i = 0; i < strCh.Length; i++)
                {
                    var chr = strCh[i];
                    fullSpell.Append(GetSpell(chr)[0]);
                }

                return fullSpell.ToString().ToUpper();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("首字母转化出错!" + e.Message);
        }

        return string.Empty;
    }


    private static string GetSpell(char chr)
    {
        var coverchr = NPinyin.Pinyin.GetPinyin(chr);

        bool isChineses = ChineseChar.IsValidChar(coverchr[0]);
        if (isChineses)
        {
            ChineseChar chineseChar = new ChineseChar(coverchr[0]);
            foreach (string value in chineseChar.Pinyins)
            {
                if (!string.IsNullOrEmpty(value))
                {
                    return value.Remove(value.Length - 1, 1);
                }
            }
        }

        return coverchr;

    }
}

参考大佬连接: fanny_atg

https://www.cnblogs.com/fannyatg/p/9167838.html

你可能感兴趣的:(C#,unity3d)