ILearnable .Net

February 20, 2014

Truncate a string without truncating/cutting words (if possible)

Filed under: Uncategorized — andreakn @ 15:04

heres a small snippets we’ve used to try and cut a string at a certain position, but accepting up to N extra letters if that means that we will not truncate in the middle of a word

   public static string TruncateAtWord(this string input, int length, int extraLength = 5)
        {
            var absoluteMaxLength = length + extraLength;
            if (input == null || input.Length < absoluteMaxLength)
            {
                return input;
            }
            var nextSpace = input.LastIndexOf(" ", absoluteMaxLength, StringComparison.Ordinal);
            return string.Format("{0}...", input.Substring(0, (nextSpace > 0) ? nextSpace : length).Trim());
        }
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: