Geeks With Blogs

News

qrcode

Lance Robinson

Create Your Badge

Lance Robinson is a software engineer in Durham, Chapel Hill, Raleigh, and surrounding areas. More about Lance.

 Subscribe


Lance's TextBox » About Me » My Resume »Twitter

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”.

    /// <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;
    }
Technorati Tags: ,
Posted on Monday, August 16, 2010 3:28 PM Programming | Back to top


Comments on this post: CSharp TruncateAtWhitespace Function

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Lance Robinson | Powered by: GeeksWithBlogs.net