C# – Limit Paragraph Length using Simple Extension Method

Happy New Year 2016 !

In most of the web applications, you will encounter a scenario where you have to display the summary of the page in limited amount of space. For example, on a section level page, sometimes you are required to display sub section summary information but due to design constraints, you can only display 80 characters.

The .NET framework provides .Substring() method to limit the string length and generate a new sub-string but this method is not clever enough to distinguish between words and empty spaces in a long paragraph and can result in a sub-string where a word has been truncated in the middle of being displayed, giving bad output to the end user.  How can we solve this ?

Here is a simple string extension method that will nicely truncate the paragraph and it will also add “…” at the end of the returned string value.

Step 1 : Add this extension method class in your project

namespace StringExtensions.LimitSentenceLength
{
    public static class StringExtensions
    {
        public static string LimitSentenceLength(this string paragraph, int maximumLenght)
        {
            //null check
            if (paragraph == null) return null;

            //less than maximum length, return as it is
            if (paragraph.Length <= maximumLenght) return paragraph; 
            //split the paragraph into indvidual words 
            string[] words = paragraph.Split(' '); 
            //initialize return variable 
            string paragraphToReturn = string.Empty; 
            //construct the return word 
            foreach (string word in words) 
           { 
            //check if adding 3 to current length and next word is more than maximum length. 
            if ((paragraphToReturn.Length + word.Length + 3) > maximumLenght)
            {
              //append "..."
              paragraphToReturn = paragraphToReturn.Trim() + "...";
              //exit foreach loop
              break;
             }
             //add next word and continue
             paragraphToReturn += word + " ";
            }
           return paragraphToReturn;
        }
    }
}

Step 2 : From your main application, you can call this method as following :

using System;

namespace StringExtensions.LimitSentenceLength
{
    class Program
    {
        private static string Paragraph => "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

        static void Main(string[] args)
        {
            Console.WriteLine(Paragraph.LimitSentenceLength(50));
            //Lorem ipsum dolor sit amet, consectetur...
            Console.WriteLine(Paragraph.LimitSentenceLength(100));
            //Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut...
            Console.WriteLine(Paragraph.LimitSentenceLength(150));
            //Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam,...
            Console.WriteLine(Paragraph.LimitSentenceLength(200));
            //Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut...
        }
   
    }
}

How simple is that !!!

Sample code is available on GitHub

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.