Home > Asp.net > Truncate Strings At Complete Words without chopping words half way In C#, Asp.net

Truncate Strings At Complete Words without chopping words half way In C#, Asp.net


There is always a common need to display n number of characters of a string and then….
But it regular practice we lose the characters displaying incomplete word.
For Eg. This is an example of long string
Now what happens when we use substring(..), the result will be
This is an example o…
It left the word “of” incomplete, chopping off the words in half way. To avoid below are the solutions to it.

public static string TruncateWithoutChopping(this string strText, int intLength)
{
    if (strText == null || strText.Length < intLength)
        return strText;
    int intNextSpace = strText.LastIndexOf(" ", intLength);
    return string.Format("{0}...", strText.Substring(0, (intNextSpace > 0) ? intNextSpace: strText).Trim());
}

Another Extension method is as follows:

public static string TruncateWithoutChopping (this string strText, int intLength)
  {
    if(String.IsNullOrEmpty(strText))
      throw new ArgumentNullException(s);
    var words = strText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    var sbText = new StringBuilder();

    foreach (var word in words.Where(word => (sbText.ToString().Length + word.Length) <= intLength))
    {
      sbText.Append(word + " ");
    }
    return sbText.ToString().TrimEnd(' ') + "...";
  }

Advertisements
  1. April 18, 2013 at 9:45 am

    Hi there mates, its enormous paragraph on the topic of tutoringand completely defined, keep it up all the time.

  1. No trackbacks yet.

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

%d bloggers like this: