欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-18 15:37:58
代码一 /// /// 截断字符串 /// ///

代码一

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