using System.Text.RegularExpressions;
namespace System
{
/// <summary>
/// 字符串助手类
/// </summary>
public static class StringHelper
{
#region 字符串扩展方法
#region 获取字符串长度(中英混合-字节截取方式)
/// <summary>
/// 获取字符串长度(中英混合-字节截取方式)
/// 实现思路:将一个汉字字符转换为两个字节的英文字符
/// </summary>
/// <param name="_oldstr"></param>
/// <returns></returns>
public static int GetLengthByChar(this string _oldstr)
{
int strlength = Regex.Replace(_oldstr, "[\u4e00-\u9fa5]", "aa", RegexOptions.IgnoreCase).Length;
return strlength;
}
#endregion
#region 截取字符串
/// <summary>
/// 截取字符串
/// 示例:string str = "截取字符串";
/// str.SubstringEx(4);
/// 结果:截取...
/// </summary>
/// <param name="trunLength">截断长度</param>
/// <returns>处理后的字符串</returns>
public static string SubstringEx(this string _oldstr, int trunLength)
{
string returnStr = "";
int thisStrLength = _oldstr.GetLengthByChar();//获取原字符串长度(字节截取方式)
//如果字符长度大于截取长度,则按字符截取字符
if (thisStrLength > trunLength)
{
int m = Convert.ToInt32(Math.Floor(Convert.ToDouble(trunLength / 2)));
for (int i = m; i < _oldstr.Length; i++)
{
if (_oldstr.Substring(0, i).GetLengthByChar() >= trunLength)
{
returnStr = _oldstr.Substring(0, i) + "...";
break;
}
}
}
else
{
returnStr = _oldstr;
}
return returnStr;
}
#endregion
#endregion
}
}