字符串截取

/// <summary>
        /// 字符串截取
        /// </summary>
        /// <param name="strValue">要截取的字符串</param>
        /// <param name="intLength">截取长度</param>
        /// <returns>截取之后的字符串</returns>
        public static string truncate(string strValue, int intLength)
        {
            if (strValue == null)
            {
                return string.Empty;
            }
            Regex re = new Regex("<(/)?([^ ]+?)(?: (/)| .*?)?>");
            strValue = strValue.Replace("&nbsp;", "");
            Match m = re.Match(strValue);
            if (m.Success)//纯英数
            {
                strValue = strValue.Replace(m.Value, "");
                m = re.Match(strValue);
            }
            re = new Regex(@"^[A-Za-z0-9]+$");
            m = re.Match(strValue);
            if (m.Success)
            {
                if (strValue.Length > intLength)
                {
                    return strValue.Substring(0, intLength) + "...";
                }
                return strValue;

            }

//混合

            byte[] bytes = System.Text.Encoding.Unicode.GetBytes(strValue);
            int n = 0;  //  表示当前的字节数
            int i = 0;  //  要截取的字节数
            for (; i < bytes.GetLength(0) && n < intLength; i++)
            {


                //  偶数位置,如0、2、4等,为UCS2编码中两个字节的第一个字节
                if (i % 2 == 0)
                {
                    n++;      //  在UCS2第一个字节时n加1
                }
                else
                {


                    //  当UCS2编码的第二个字节大于0时,该UCS2字符为汉字,一个汉字算两个字节
                    if (bytes[i] > 0)
                    {
                        n++;
                    }
                }
            }


            //  如果i为奇数时,处理成偶数


            if (i % 2 == 1)
            {
                //  该UCS2字符是汉字时,去掉这个截一半的汉字


                if (bytes[i] > 0)
                    i = i - 1;


                 //  该UCS2字符是字母或数字,则保留该字符
                else
                    i = i + 1;
            }
            if (bytes.Length > intLength)
            {
                strValue = System.Text.Encoding.Unicode.GetString(bytes, 0, i) + "...";
            }
            else
            {
                strValue = System.Text.Encoding.Unicode.GetString(bytes, 0, i);


            }
            return strValue;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值