C# unity 中實現漢字轉拼音

首先下載安裝必要的庫文件

安裝後的地址

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

在文件夾下放入這幾個庫文件

會遇到unity中打包後,出現 Encoding.GetEncoding("GB2312")  把這兩個文件複製放入到  libs 下就行了

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");

    /// <summary>
    /// 漢字轉全拼
    /// </summary>
    /// <param name="strCh"></param>
    /// <returns></returns>
    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;
    }

    /// <summary>
    /// 漢字轉首字母
    /// </summary>
    /// <param name="strCh"></param>
    /// <returns></returns>
    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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章