Intelligent clipping routine

This is an intelligent text-clipping routine. If the text if too long it tries to clip out the last words of the text string untill the length is shorter than the designated length.
If there is no more spaces and the text is still too long it truncates the remaining word untill the length is below maximum.

public static string Clip(string Text, int Length, bool Ellipsis)
  if (Text.Length <= Length)
    return Text;
  while (Text.Length > Length)
    int lastSpace = Text.LastIndexOf(" ");
    if (lastSpace == -1)
      if (Ellipsis)
        return Text.Substring(0, Length) + "...";
      return Text.Substring(0, Length);
    Text = Text.Remove(lastSpace, Text.Length-lastSpace);
  if (Ellipsis)
    return Text + "...";
  return Text;

The “Ellipsis” parameter appends epplisises (…) to the concatenated string.

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in General .NET and tagged . Bookmark the permalink.

Leave a Reply

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

You are commenting using your 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