獲取中文首字母


/// <summary>
/// 判斷是否爲漢字
/// </summary>
/// <param name="chrStr">待檢測字符串</param>
/// <returns>是漢字返回true</returns>
public bool IsChineseCharacters(string chrStr)
{
Regex CheckStr = new Regex("[\u4e00-\u9fa5]");
return CheckStr.IsMatch(chrStr);
}編碼

/// <summary>
/// 獲得每一個漢字的字首拼音碼字母(大寫)
/// </summary>
/// <param name="chrStr">輸入字符串</param>
/// <returns>返回結果</returns>
public string GetHeadCharacters(string chrStr)
{
string strHeadString = string.Empty;字符串

Encoding gb = System.Text.Encoding.GetEncoding("gb2312");
for (int i = 0; i < chrStr.Length; i++)
{
//檢測該字符是否爲漢字
if (!IsChineseCharacters(chrStr.Substring(i, 1)))
{
strHeadString += chrStr.Substring(i, 1);
continue;
}string

byte[] bytes = gb.GetBytes(chrStr.Substring(i, 1));
string lowCode = System.Convert.ToString(bytes[0] - 0xA0, 16);
string hightCode = System.Convert.ToString(bytes[1] - 0xA0, 16);
int nCode = Convert.ToUInt16(lowCode, 16) * 100 + Convert.ToUInt16(hightCode, 16); //獲得區位碼
strHeadString += FirstLetter(nCode);
}
return strHeadString;
}coding

/// <summary>
/// 經過漢字區位碼獲得其首字母(大寫)
/// </summary>
/// <param name="nCode">漢字編碼</param>
/// <returns></returns>
public string FirstLetter(int nCode)
{
if (nCode >= 1601 && nCode < 1637) return "A";
if (nCode >= 1637 && nCode < 1833) return "B";
if (nCode >= 1833 && nCode < 2078) return "C";
if (nCode >= 2078 && nCode < 2274) return "D";
if (nCode >= 2274 && nCode < 2302) return "E";
if (nCode >= 2302 && nCode < 2433) return "F";
if (nCode >= 2433 && nCode < 2594) return "G";
if (nCode >= 2594 && nCode < 2787) return "H";
if (nCode >= 2787 && nCode < 3106) return "J";
if (nCode >= 3106 && nCode < 3212) return "K";
if (nCode >= 3212 && nCode < 3472) return "L";
if (nCode >= 3472 && nCode < 3635) return "M";
if (nCode >= 3635 && nCode < 3722) return "N";
if (nCode >= 3722 && nCode < 3730) return "O";
if (nCode >= 3730 && nCode < 3858) return "P";
if (nCode >= 3858 && nCode < 4027) return "Q";
if (nCode >= 4027 && nCode < 4086) return "R";
if (nCode >= 4086 && nCode < 4390) return "S";
if (nCode >= 4390 && nCode < 4558) return "T";
if (nCode >= 4558 && nCode < 4684) return "W";
if (nCode >= 4684 && nCode < 4925) return "X";
if (nCode >= 4925 && nCode < 5249) return "Y";
if (nCode >= 5249 && nCode < 5590) return "Z";
return "";
}di

public void StaticGetHeadCharacters(string chrStr)
{//讀取對應的首字母
string a = GetHeadCharacters(chrStr);
}co

相關文章
相關標籤/搜索