c#完美截断字符串代码(中文+非中文)

来源:互联网 发布:哪里可以买到淘宝店铺 编辑:程序博客网 时间:2024/05/20 12:22
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
    }
}
0 0
原创粉丝点击