按字节剪切文章标题

  在做Web开发时,我们经常需要对过长的文章标题剪切,一般剪切方法是按字符数剪切,出现中文与英文标题会出现长短不一。为此写了一个按照字节剪切字符串的工具方法。

 /// <summary>
        /// 按字节剪切字符串的方法
        /// </summary>
        /// <param name="content"> 需要剪切的内容 </param>
        /// <param name="maxLength"> 需要显示的最大长度 </param>
        /// <returns> 剪切后的字符串 </returns>
        public static string SubStringByByte(string content, int maxLength)
        {
            if (GetBytelenght(content) > maxLength)
            {
                return content.Substring(0, GetSubLenth(content, maxLength)) + "....";
            }
            return content;
        }

        /// <summary>
        /// 获取字符串的字节长度
        /// </summary>
        /// <param name="content"> 字符串 </param>
        /// <returns> 字节长度 </returns>
        public static int GetBytelenght(string content)
        {
            if (string.IsNullOrWhiteSpace(content)) return 0;
            byte[] bytestr = Encoding.Unicode.GetBytes(content);
            int j = 0;
            for (int i = 0; i < bytestr.GetLength(0); i++)
            {
                if (i % 2 == 0)
                {
                    j++;
                }
                else
                {
                    if (bytestr[i] > 0)
                    {
                        j++;
                    }
                }
            }
            return j;
        }

        /// <summary>
        /// 获取需要剪切的Index
        /// </summary>
        /// <param name="content"> 字符串 </param>
        /// <param name="max"> 需要显示最大字节数 </param>
        /// <returns> 需要剪切的Index </returns>
        public static int GetSubLenth(string content, int max)
        {
            if (string.IsNullOrWhiteSpace(content)) return 0;
            byte[] bytestr = Encoding.Unicode.GetBytes(content);
            int j = 0;
            int i = 0;
            for (; i < bytestr.GetLength(0); i++)
            {
                if (i % 2 == 0)
                {
                    j++;
                }
                else
                {
                    if (bytestr[i] > 0)
                    {
                        j++;
                    }
                }
                if (j == max)
                {
                    return i / 2;
                }
            }
            return i / 2;
        }
    }

  调用方法:

  

    string content = "dfsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa阿斯顿发送的发顺丰";
            string content1 = "1231231312三四五六31231231213123123123123123123一二三四五六七八九十";
            int maxLenth = 40;
            Console.WriteLine(SubStringByByte(content, maxLenth));
            Console.WriteLine(SubStringByByte(content1, maxLenth));

            Console.ReadKey();

  显示结果:

原文地址:https://www.cnblogs.com/dyfzwj/p/2655797.html