C# 获取汉字拼音的首写字母
第一次写博客,不足之处请大家谅解
展开
1 /// <summary>
2 /// 获取单个汉字的首写拼音字母
3 /// </summary>
4 /// <param name="cn"></param>
5 /// <returns></returns>
6 public static string getSpell(string cn)
7 {
8 #region
9 byte[] arrCN = Encoding.Default.GetBytes(cn);
10 if (arrCN.Length > 1)
11 {
12 int area = (short)arrCN[0];
13 int pos = (short)arrCN[1];
14 int code = (area << 8) + pos;
15 int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };
16 for (int i = 0; i < 26; i++)
17 {
18 int max = 55290;
19 if (i != 25) max = areacode[i + 1];
20 if (areacode[i] <= code && code < max)
21 {
22 return Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
23 }
24 }
25 return cn;
26 }
27 else return cn;
28 #endregion
29 }
30
31 /// <summary>
32 /// 获取汉字字符串的首写英文字母
33 /// </summary>
34 /// <param name="str"></param>
35 /// <returns></returns>
36 public static string GetStringSpell(string str)
37 {
38 char[] chars = str.ToCharArray();
39 string result = "";
40 if (chars.Length > 1)
41 {
42 for (int i = 0; i < chars.Length; i++)
43 {
44 result += getSpell(chars[i].ToString());
45 }
46 }
47 else if (chars.Length == 1)
48 {
49 result = getSpell(str);
50 }
51
52 return result.ToLower();
53
54
2 /// 获取单个汉字的首写拼音字母
3 /// </summary>
4 /// <param name="cn"></param>
5 /// <returns></returns>
6 public static string getSpell(string cn)
7 {
8 #region
9 byte[] arrCN = Encoding.Default.GetBytes(cn);
10 if (arrCN.Length > 1)
11 {
12 int area = (short)arrCN[0];
13 int pos = (short)arrCN[1];
14 int code = (area << 8) + pos;
15 int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };
16 for (int i = 0; i < 26; i++)
17 {
18 int max = 55290;
19 if (i != 25) max = areacode[i + 1];
20 if (areacode[i] <= code && code < max)
21 {
22 return Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
23 }
24 }
25 return cn;
26 }
27 else return cn;
28 #endregion
29 }
30
31 /// <summary>
32 /// 获取汉字字符串的首写英文字母
33 /// </summary>
34 /// <param name="str"></param>
35 /// <returns></returns>
36 public static string GetStringSpell(string str)
37 {
38 char[] chars = str.ToCharArray();
39 string result = "";
40 if (chars.Length > 1)
41 {
42 for (int i = 0; i < chars.Length; i++)
43 {
44 result += getSpell(chars[i].ToString());
45 }
46 }
47 else if (chars.Length == 1)
48 {
49 result = getSpell(str);
50 }
51
52 return result.ToLower();
53
54