.NET Hobbyist Programmer

Staying Confused in a Busy World
posts - 271, comments - 284, trackbacks - 660

My Links

News

Neat Stuff Read all my hurricane entries While you are here, visit the Geeks With Blogs main feed
Advertising
Links Status of the Navy
Channel 9

Tag Cloud

Article Categories

Archives

Post Categories

String.Truncate

After my previous post on truncating a .NET String at the end of a word, I thought that the simpler problem of just truncating a string to a specific length, while retaining all the rest of the code’s features, would have been obvious, but I got a couple of email requests.  So here it is.

/// <summary>
/// Truncate a string to the specified length.
/// </summary>
/// <param name="value">The input string.</param>
/// <param name="length">The maximum length of the returned string.</param>
/// <returns>>A substring of the original, truncated to the specified length.</returns>
public static String Truncate(this String value, int length)
{
  return value.Truncate(length, false);
}
 
/// <summary>
/// Truncate a string to the specified length.
/// </summary>
/// <param name="value">The input string.</param>
/// <param name="length">The maximum length of the returned string.</param>
/// <param name="addEllipsis">Specifies whether an ellipsis (...) is added to the end of the string.</param>
/// <returns>>A substring of the original, truncated to the specified length.</returns>
public static String Truncate(this String value, int length, bool addEllipsis)
{
  // Return unchanged if no truncation required
  if ((value == null) || (value.Length <= length) || (length <= 0))
  {
    return value;
  }
  // Ensure length meets conditions
  if (addEllipsis && (length > 3))
  {
    length -= 3;
  }
  else
  {
    addEllipsis = false;
  }
  // Truncate based on passed length
  String work = value.Substring(0, length);
  // Optionally add ellipsis
  return (addEllipsis ? (work + "...") : work);
}
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Print | posted on Saturday, August 28, 2010 10:32 PM | Filed Under [ Programming ]

Feedback

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

Powered by: