C Chinese and English mixed string interceptor function

  • 2020-05-17 06:17:25
  • OfStack

Code 1


/// <summary>
    ///  Truncated string 
    /// </summary>
    /// <param name="maxLength"> The maximum length </param>
    /// <param name="str"> The original string </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 "...";
    }

Code 2


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;
    }

Above is the implementation code of C# intercepting string method (including Chinese and English mixture), you can refer to 1


Related articles: