C#中英文混合字符串截取函数_技术学院_宜昌市隼壹珍商贸有限公司

您好,欢迎访问宜昌市隼壹珍商贸有限公司

400 890 5375
当前位置: 主页 > 新闻动态 > 技术学院

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

发布时间:2026-01-17  |  点击率:

代码一

/// <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# 截取字符串方法(包含中英混合)的实现代码,需要的朋友可以参考一下

全国统一服务电话

400 890 5375

电子邮箱:879577@qq.com

公司地址:宜昌市西陵区黄河路5号三峡明珠10栋1051室

咨询微信

TEL:13680874598