字符串长度截取换行/n

      ///


        /// 格式化字符串长度,超出部分显示省略号,区分汉字跟字母。汉字2个字节,字母数字一个字节
        ///

        /// 字符串
        /// 截取长度
        ///
        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;
            }
        }

        ///


        /// 字符串长度换行/n 返回StringBuilder
        ///

        /// str
        /// 限制字节长度
        ///
        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

你可能感兴趣的:(字符串长度截取换行/n)