首页 > 编程 > C# > 正文

C# 汉字转化拼音的简单实例代码

2020-01-24 03:27:52
字体:
来源:转载
供稿:网友

首先引入ChnCharInfo.dll 第3方的一个库

代码:

btn_chinChar_Click事件:

复制代码 代码如下:

private void btn_chinChar_Click(object sender, EventArgs e)
        {
            ChineseChar cr =null;
            string str = "", txtString = txt_string.Text.Trim();
            if (!string.IsNullOrEmpty(txtString))
            {
                foreach (var item in cr.GetChineseSpellings(txtString))
                {
                    str += item + "-";
                }
            }
            MessageBox.Show(str);
        }

扩展方法:

复制代码 代码如下:

public static class ChineseCharacters
    {
        public static ICollection<string> GetChineseSpellings(this ChineseChar chinChar ,string value)
        {
            List<string> list;
            int i,start;
            char c;

            if (string.IsNullOrEmpty(value))return null;

            start = 0;
            list = new List<string>();

            for (i = 0; i < value.Length; ++i)
            {
                c = value[i];
                if (ChineseChar.IsValidChar(c))
                {
                    if (i > start)
                    {
                        list.Add(value.Substring(start, i - start));
                    }
                    chinChar = new ChineseChar(c);
                    list.Add(chinChar.Pinyins.First().Substring(0, chinChar.Pinyins.First().Length - 1).ToLower());
                    start = i + 1;
                }
            }

            if (i > start)
            {
                list.Add(value.Substring(start, i - start));
            }
            return list;
        }
    }


运用结果:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表