字符串长度截取换行/n

      /// <summary>
        /// 格式化字符串长度,超出部分显示省略号,区分汉字跟字母。汉字2个字节,字母数字一个字节
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="n">截取长度</param>
        /// <returns></returns>
        public static string Substringforlength(string str, int n)
        {
            string temp = string.Empty;
            if (System.Text.Encoding.Default.GetByteCount(str) <= n)//如果长度比需要的长度n小,返回原字符串
            {
                return str;
            }
            else
            {
                int t = 0;
                char[] q = str.ToCharArray();
                for (int i = 0; i < q.Length; i++)
                {
                    if ((int)q[i] >= 0x4E00 && (int)q[i] <= 0x9FA5)//是否汉字
                    {
                        temp += q[i];
                        t += 2;
                    }
                    else
                    {
                        temp += q[i];
                        t += 1;
                    }
                    if (t >= n)
                    {
                        break;
                    }
                }
                return temp;
            }
        }

        /// <summary>
        /// 字符串长度换行/n 返回StringBuilder
        /// </summary>
        /// <param name="str">str</param>
        /// <param name="length">限制字节长度</param>
        /// <returns></returns>
        public static string returnstr(string str, int length)
        {
            StringBuilder sb = new StringBuilder();
            string str1="", str2 = "";
            int len = getLen(str);
            int num = len / length+ (len % length == 0 ? 0 :1);           
            int strlength =0;
          
            for (int i = 0; i < num; i++)
            {
                if (System.Text.Encoding.Default.GetByteCount(str) > length)
                {
                    str1 = Substringforlength(str, length);
                    sb.Append(str1 + "/n");
                    strlength = str1.Length;
                    str2 = str.Substring(strlength);
                    str = str2;
                }
                else {                  
                    sb.Append(str + "/n");
                    str = "";
                }
            }
            return sb.ToString();

        }

转载于:https://www.cnblogs.com/pengde/p/5265436.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值