VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C#教程之C# 汉字转化拼音的简单实例代码

首先引入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;
        }
    }


运用结果:

 


相关教程