``` //判断是否是汉字 public static bool IsChinese(char chr) { return (int)chr > 0x4E00 && (int)chr < 0x9FA5; } /// <summary> /// 截取字符串,不限制字符串长度 /// </summary> /// <param name="str">待截取的字符串</param> /// <param name="len">每行的长度,多于这个长度自动换行</param> /// <returns></returns> public static string GetStringByLen(string str, int len) { //正常情况下,我们是直接去string的length的,但是汉字是有多个字节的 StringBuilder sb = new StringBuilder(); int count = 0;//统计个数 for (int i = 0; i < str.Length; i++) { char chr = str[i]; count += GetStrLength(chr.ToString(), Encoding.UTF8); if (count == len) { sb.Append(chr + "\r\n"); count = 0; } else if (count > len) { sb.Append("\r\n" + chr); count = GetStrLength(chr.ToString(), Encoding.UTF8); } else { sb.Append(chr); } } return sb.ToString(); } /// <summary> /// 获取字符串长度 /// </summary> /// <param name="str">字符串</param> /// <param name="encoding">编码格式</param> /// <returns></returns> public static int GetStrLength(string str,Encoding encoding) { //默认字节长度:中文占两个字节,其他占一个字节 //utf-8字节长度:中文占三个字节,其他占一个字节 return encoding.GetByteCount(str); } /// <summary> /// 根据字符串长度拆成集合 /// </summary> /// <param name="value"></param> /// <param name="len"></param> /// <returns></returns> public static List<string> GetStringList(string value,int len = 30) { var strings = GetStringByLen(value,len).Split("\r\n").ToList(); strings.RemoveAll(t => string.IsNullOrEmpty(t)); return strings; } ```
C# 折叠 复制 全屏