C# 漢字轉(zhuǎn)化拼音的簡單實例代碼
首先引入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;
}
}
運用結(jié)果:
相關(guān)文章
c#之用戶定義的數(shù)據(jù)類型轉(zhuǎn)換介紹
c#允許定義自己的數(shù)據(jù)類型,這意味著需要某些工具支持在自己的數(shù)據(jù)類型間進行數(shù)據(jù)轉(zhuǎn)換。方法是把數(shù)據(jù)類型轉(zhuǎn)換定義為相關(guān)類的一個成員運算符,數(shù)據(jù)類型轉(zhuǎn)換必須聲明是隱式或者顯式,以說明怎么使用它2014-01-01