.Net mvc自定义字符串截取(考虑全角/半角)

public static class HtmlHelpers
{
  public static string Truncate(this HtmlHelper helper, string inputString, int length)
  {
    string tempString = string.Empty;
    for (int i = 0, tempIndex = 0; i < inputString.Length; ++i, ++tempIndex)
    {
      if (System.Text.Encoding.UTF8.GetBytes(new char[] { inputString[i] }).Length > 1)
      {
        ++tempIndex;
      }
      if (tempIndex >= length)
      {
        tempString += "...";
        break;
      }
      tempString += inputString[i];
    }
    return tempString;
  }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注