posts - 598 , comments - 849 , trackbacks - 247

My Links

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

Tag Cloud

Archives

Post Categories

Blogs

Miscellanous

Noteworthy Stuff

Popular Posts

CSharp TruncateAtWhitespace Function

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: ,

Print | posted on Monday, August 16, 2010 3:28 PM | Filed Under [ Programming ]

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: