C#中实现中文转拼音的功能
在此之前,我们需要一个安装包,这个用来实现中文到拼音的转换:
Microsoft Visual Studio International Pack 1.0 SR1 :http://www.microsoft.com/zh-cn/download/details.aspx?id=15251
下载好安装包,解压后可以看见如下图:
图-1
然后选择 CHSPinYinConv进行安装,安装后的文件夹如图:
图-2
在项目的Reference中添加 ChnCharInfo.dll, 然后 Build。至于为啥要添加这个,可以从图-3左下角的程序集看出来。
图-3
准备工作完成后,进入下面程序代码的编写:
//------------------------------------------------------------1 主窗体---------------------------------------------------------------------------
主窗体:两个Label, 两个TextBox,一个Button
图-4
//------------------------------------------------------------2 Program.cs---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _12中文转拼音
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
//------------------------------------------------------------3 Form1.cs---------------------------------------------------------------------------
using Microsoft.International.Converters.PinYinConverter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _12中文转拼音
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnChange_Click(object sender, EventArgs e)
{
StringBuilder sbpy = new StringBuilder();
// 1. 获取用户输入的中文
string userInput = txtChinese.Text.Trim();
// 2. 遍历用户输入的字符串中的每个字符
for (int i = 0; i < userInput.Length; i++)
{
// 3. 判断是否为合法字符,是否有读音
if (ChineseChar.IsValidChar(userInput[i]))
{
// 4. 获取该汉字的拼音
ChineseChar chn=new ChineseChar(userInput[i]);
if (chn.Pinyins.Count > 0)
{
string py = chn.Pinyins[0].Substring(0, chn.Pinyins[0].Length - 1);
sbpy.Append(py);
}
}
txtPinyin.Text = sbpy.ToString();
}
}
}
}