CSharp TruncateAtWhitespace Function

Visual Studio

Here’s a TruncateAtWhitespace function that takes an incoming parameter value and an incoming max length, and returns a substring broken at a whitespace position.  This way if you have “Lance has a blog” and you need to truncate it to 8 characters or less, you get “Lance…” instead of “Lance ha”.

PowerShell
    /// <summary>
    /// Truncate at the end of a word
    /// </summary>
    /// <param name="value">The original string</param>
    /// <param name="maxlength">The maximum length of string to return</param>
    /// <returns>A substring of the original, broken at the end of a word</returns>
    public static string TruncateAtWhitespace(string value, int maxlength)
    {
      maxlength = maxlength - 3; //allow for ending "..."
   
      if (value.Length <= maxlength) return value + "...";

      int closestwhitespaceindex = value.Substring(0, maxlength).LastIndexOf(" ");
      if (closestwhitespaceindex > 0)
      {
        value = value.Substring(0, closestwhitespaceindex) + "...";
      }
      else
      {
        value = value.Substring(0, maxlength);
      }

      return value;
    }
PowerShell

Leave a Reply

Your email address will not be published. Required fields are marked *