New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

TextAbstract Method

349 Views
Copy Code Show/Hide Line Numbers
/// <summary>
/// Returns an abstract of the provided text by returning up to Length characters
/// of a text string. If the text is truncated a ... is appended.
/// </summary>
/// <param name="Text">Text to abstract</param>
/// <param name="Length">Number of characters to abstract to</param>
/// <returns>string</returns>
public static string TextAbstract(string Text, int Length)
{
    if (Text.Length <= Length)
        return Text;
 
    Text = Text.Substring(0, Length - 2);
 
    Text = Text.Substring(0, Text.LastIndexOf(" "));
    return Text + "...";
}
by Rick Strahl
  July 20, 2009 @ 5:32pm
Tags:
Comment:
A simple function to truncate a string on a word boundary with an ellipsis if text exceeds a specified length.

by Al Gonzalez    July 20, 2009 @ 8:26pm

If the initial substring returns a text ending in a space or a space followed by a single letter such as 'I' or 'a', then your actual length after adding the three character ellipse will be more than the requested length.

by Rick Strahl    July 21, 2009 @ 2:18am

Ah good point. For me the length specifies the length of characters without the elipsis character. I suppose making it Length-2 would do the trick.

Add a comment


Report Abuse
brought to you by:
West Wind Techologies


If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate