本文轉自:http://www.cnblogs.com/yazdao/archive/2011/06/04/2072488.html
昨天經過網友提示,提取漢字拼音的辦法可以應用微軟的一個類庫 Visual Studio International Pack ,今天試了一試,確切好用!下面分享下應用辦法:
起首下載Visual Studio International Pack 1.0,官方:http://www.microsoft.com/downloads/zh-cn/details.aspx?FamilyID=44CAC7F0-633B-477D-AED2-99AEE642FC10&displaylang=zh-cn。下載完畢後解壓,解壓後可以發明7個MSI安裝檔案,此中CHSPinYinConv.msi是漢字拼音組件,CHTCHSConv.msi是進行繁簡體互轉組件,安裝這兩個MSI就可以了 (x86操縱體繫上的預設安裝目次是 C:\Program Files\Microsoft Visual Studio International Pack\) 。安裝完畢後,須要在VS裡添加引用,分別引用:C:\Program Files\Microsoft Visual Studio International Pack\Simplified Chinese Pin-Yin Conversion Library(拼音)下和C:\Program Files\Microsoft Visual Studio International Pack\Traditional Chinese to Simplified Chinese Conversion Library and Add-In Tool(繁簡互轉)下的dll 即可應用。
完成上方的工作後,應用辦法就很是簡單了,下面看代碼:
using Microsoft.International.Converters.PinYinConverter;//匯入拼音相干
namespace WebApplication2
{
public class Class1
{
/// <summary>
/// 漢字轉化為拼音
/// </summary>
/// <param name="str">漢字</param>
/// <returns>全拼</returns>
public static string GetPinyin(string str)
{
string r = string.Empty;
foreach (char obj in str)
{
try
{
ChineseChar chineseChar = new ChineseChar(obj);
string t = chineseChar.Pinyins[0].ToString();
r += t.Substring(0, t.Length - 1);
}
catch
{
r += obj.ToString();
}
}
return r;
}
/// <summary>
/// 漢字轉化為拼音首字母
/// </summary>
/// <param name="str">漢字</param>
/// <returns>首字母</returns>
public static string GetFirstPinyin(string str)
{
string r = string.Empty;
foreach (char obj in str)
{
try
{
ChineseChar chineseChar = new ChineseChar(obj);
string t = chineseChar.Pinyins[0].ToString();
r += t.Substring(0, 1);
}
catch
{
r += obj.ToString();
}
}
return r;
}
}
}
複製代碼
調用辦法:(重視先引用)
GetPinyin("風影");//擷取全拼
GetFirstPinyin("風影");//擷取首字母
是不是很是簡單呢?有了這個類庫就省事多了!趁便再補充一下繁簡體互轉的辦法,某些時辰可能會用到:
先匯入
using Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter;
/// <summary>
/// 簡體轉換為繁體
/// </summary>
/// <param name="str">簡體字</param>
/// <returns>繁體字</returns>
public static string GetTraditional(string str)
{
string r = string.Empty;
r = ChineseConverter.Convert(str, ChineseConversionDirection.SimplifiedToTraditional);
return r;
}
/// <summary>
/// 繁體轉換為簡體
/// </summary>
/// <param name="str">繁體字</param>
/// <returns>簡體字</returns>
public static string GetSimplified(string str)
{
string r = string.Empty;
r = ChineseConverter.Convert(str, ChineseConversionDirection.TraditionalToSimplified);
return r;
}
複製代碼
該類庫的功能概述
Microsoft Visual Studio International Pack 1.0版 包含以下功能: