C#中英文混合字符串截取函数

作者:shangke 时间:2023-01-19 06:02:55 

代码一


/// <summary>
   /// 截断字符串
   /// </summary>
   /// <param name="maxLength">最大长度</param>
   /// <param name="str">原字符串</param>
   /// <returns></returns>
   public static string CutStr(int maxLength, string str)
   {
     string temp = str;
     if (Regex.Replace(temp, "[\u4e00-\u9fa5]", "zz", RegexOptions.IgnoreCase).Length <= maxLength)
     {
       return temp;
     }
     for (int i = temp.Length; i >= 0; i--)
     {
       temp = temp.Substring(0, i);
       if (Regex.Replace(temp, "[\u4e00-\u9fa5]", "zz", RegexOptions.IgnoreCase).Length <= maxLength - 3)
       {
         return temp + "...";
       }
     }
     return "...";
   }

代码二


private string GetByteString(string center, int maxlen, string endStr)
   {
     string temp = center.Substring(0, (center.Length < maxlen + 1) ? center.Length : maxlen + 1);
     byte[] encodedBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(temp);
     string outputStr = "";
     int count = 0;
     for (int i = 0; i < temp.Length; i++)
     {
       if ((int)encodedBytes[i] == 63)
         count += 2;
       else
         count += 1;

if (count <= maxlen - endStr.Length)
         outputStr += temp.Substring(i, 1);
       else if (count > maxlen)
         break;
     }
     if (count <= maxlen)
     {
       outputStr = temp;
       endStr = "";
     }
     outputStr += endStr;
     return outputStr;
   }
标签:C#,中英文,字符串截取
0
投稿

猜你喜欢

  • springcloud中Ribbon和RestTemplate实现服务调用与负载均衡

    2022-06-30 14:58:45
  • mybatis-plus自动填充插入更新时间有8小时时差

    2021-07-26 07:18:40
  • C#语言中条件与&&与条件或||的区别

    2022-10-06 22:51:55
  • Android中FoldingLayout折叠布局的用法及实战全攻略

    2021-05-23 19:29:17
  • Java读取properties配置文件的8种方式汇总

    2022-05-03 17:11:34
  • mybatisplus中EntityWrapper的常用方法

    2022-11-09 21:52:00
  • C#连接ODBC数据源的方法

    2023-04-20 07:30:33
  • C++内存对齐的实现

    2023-11-22 00:42:20
  • 基于Hibernate中配置文件的学习(分享)

    2022-02-11 12:03:31
  • Java中对象的比较操作实例分析

    2023-03-05 03:58:09
  • Android App开发中自定义View和ViewGroup的实例教程

    2021-06-11 08:58:03
  • Android RIL使用详解

    2021-09-30 18:06:45
  • Android开发中Intent.Action各种常见的作用汇总

    2022-10-08 10:24:53
  • SpringBoot接口调用之后报404问题的解决方案

    2021-08-31 15:25:03
  • Java 中 hashCode() 与 equals() 的关系(面试)

    2023-08-29 18:03:57
  • C#截图程序类似腾讯QQ截图实现代码

    2023-05-07 04:01:01
  • Spring Boot集成MyBatis的方法

    2021-11-03 23:11:05
  • 详解C#使用AD(Active Directory)验证内网用户名密码

    2023-03-03 23:17:47
  • mybatis中的if test判断入参的值问题

    2023-11-16 08:13:44
  • C++类中的特殊成员函数示例详解

    2023-11-07 13:02:08
  • asp之家 软件编程 m.aspxhome.com