#region << 版 本 注 释 >> /**************************************************** * 文 件 名:RegExpHelper * Copyright(c) www.ITdos.com * CLR 版本: 4.0.30319.17929 * 创 建 人:ITdos * 电子邮箱:admin@itdos.com * 创建日期:2016/05/04 23:11:36 * 文件描述: ****************************************************** * 修 改 人: * 修改日期: * 备注描述: *******************************************************/ #endregion using System; using System.Text; namespace GT.Common.Helper { /// <summary> /// 字符串帮助类 /// </summary> public class StringHelper { /// <summary> /// 获取字节数 /// str:需要获取的字符串 /// </summary> public static int Length(string str) { if (string.IsNullOrWhiteSpace(str)) { return 0; } var j = 0; var ce = str.GetEnumerator(); while (ce.MoveNext()) { j += (ce.Current > 0 && ce.Current < 255) ? 1 : 2; } return j; } /// <summary> /// 按字节数截取指定字节 /// </summary> /// <Param name="str">需要获取的字符串</Param> /// <Param name="length">获取的字节长度</Param> /// <returns></returns> public static string SubString(string str, int length) { var result = str; int j = 0, k = 0; var ce = str.GetEnumerator(); while (ce.MoveNext()) { j += (ce.Current > 0 && ce.Current < 255) ? 1 : 2; if (j <= length) { k++; } else { result = str.Substring(0, k); break; } } return result; } #region 取首字母 /// <summary> /// 获取汉字首字母(可包含多个汉字) /// </summary> /// <Param name="strText"></Param> /// <returns></returns> public static string GetChineseSpell(string strText) { int len = strText.Length; string myStr = ""; for (int i = 0; i < len; i++) { myStr += GetSpell(strText.Substring(i, 1)); } return myStr; } public static string GetSpell(string cnChar) { var arrCn = Encoding.Default.GetBytes(cnChar); if (arrCn.Length > 1) { int area = (short)arrCn[0]; int pos = (short)arrCn[1]; int code = (area << 8) + pos; 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 }; for (int i = 0; i < 26; i++) { int max = 55290; if (i != 25) max = areacode[i + 1]; if (areacode[i] <= code && code < max) { return Encoding.Default.GetString(new byte[] { (byte)(65 + i) }); } } return "*"; } return cnChar; } /// <summary> /// 获取第一个汉字的首字母,只能输入汉字 /// </summary> /// <Param name="c"></Param> /// <returns></returns> public static string GetInitial(string c) { byte[] array = new byte[2]; array = System.Text.Encoding.Default.GetBytes(c); int i = (short)(array[0] - '