Geeks With Blogs

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

.NET Hobbyist Programmer Staying Confused in a Busy World

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);
}
Posted on Saturday, August 28, 2010 10:32 PM Programming | Back to top


Comments on this post: String.Truncate

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


Copyright © Mark Treadwell | Powered by: GeeksWithBlogs.net