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

I recently worked with a friend on a small C# teaching project.  We started with the premise of writing a String Truncate function for .NET 3.5 SP 1.  At its simplest, this is trivial to create.

public String Truncate(String input, int length)
{
  return input.Substring(0, length);
}

After a review of the weaknesses of this implementation, we went in search of a more meaningful challenge.  We expanded on this first effort with a few additional requirements:

  1. Input validation
  2. Do not truncate in the middle of a word
  3. Optionally add ellipsis to truncated strings
  4. Implement as an extension method
  5. XML documentation
  6. Overloaded methods

We assumed that the truncation length was inviolable, so we had the fit the ellipsis within it.  This is what we came up with:

/// <summary>
/// Truncate a string at the end, vice the middle, of a word.
/// </summary>
/// <param name="input">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 at the end of a word.</returns>
/// <remarks>
/// This is primarily a truncate function with the ability to not leave partial words in the result.
/// The input string is returned if it is null, is less than the truncation length, or the truncation length
/// is zero or negative.  Added ellipsis reduces the returned string length by at least three characters.
/// </remarks>
public static String TruncateAtWord(this String input, int length, bool addEllipsis)
{
  // Return unchanged if no truncation required
  if ((input == null) || (input.Length <= length) || (length <= 0))
  {
    return input;
  }
  // Ensure length meets conditions
  if (addEllipsis && (length > 3))
  {
    length -= 3;
  }
  else
  {
    addEllipsis = false;
  }
  // Truncate based on passed length
  String work = input.Substring(0, length);
  // Return if truncation was at the end of a word
  if (input.Substring(length, 1) == " ")
  {
    // Optionally add ellipsis
    return (addEllipsis ? (work + "...") : work);
  }
  // Truncate again before last space in string, if any
  int lengthToSpace = work.LastIndexOf(" ");
  if (lengthToSpace > 0)
  {
    work = work.Substring(0, lengthToSpace);
  }
  // Optionally add ellipsis
  return (addEllipsis ? (work + "...") : work);
}

The inline comments are too much for a production application, but they work for this snippet.

We wrote one overload like this:

/// <summary>
/// Truncate a string at the end of a word.
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="length">The maximum length of the returned string.</param>
/// <returns>A substring of the original, truncated at the end of a word.</returns>
public static String TruncateAtWord(this String input, int length)
{
  return TruncateAtWord(input, length, false);
}

A somewhat long test looks like this.

String str = "Four score and seven years ago our fathers brought forth on this continent, a new nation, " +
             "conceived in Liberty, and dedicated to the proposition that all men are created equal.";
for (int i = str.Length; i > 0; i--)
{
  System.Diagnostics.Debug.Print(i.ToString("000") + ":  " + str.TruncateAtWord(i, true));
}

As a teaching exercise, the logic flow is straightforward, though I did include conditional (or ternary) operator statements to implement the optional ellipsis addition.  This was fun to do.  Enjoy.

Posted on Monday, August 23, 2010 7:15 PM Programming | Back to top


Comments on this post: String.TruncateAtWord

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


Copyright © Mark Treadwell | Powered by: GeeksWithBlogs.net