Categories

Tools

bitdefender

1&1 Web Hosting

Develop a C# method to obtain a "Summary" of a long text, without cutting words


This example is useful when you want to get a "Summary" short from a very long text, without cutting words.

Code:

using System;
using System.IO;

namespace ConsoleApplications
{
    class GetShortDescriptionDemo
    {
        public const int MAXIMUM_LENGTH_OF_THE_SHORT_DESCRIPTION = 200;

        static void Main(string[] args)
        {
            string longText = String.Empty;

            // Load text from a file
            string pathOfFile = "LoremIpsum.txt";

            try 
            {
                StreamReader sr = new StreamReader(pathOfFile);
                longText = sr.ReadToEnd();
            }
            catch(Exception excp)
            { }

            string shortText = GetShortDescription(longText);

            Console.WriteLine("Long text (lenght:{0} chars)\n{1}", longText.Length, longText);
            Console.WriteLine();
            Console.WriteLine("Short text (lenght:{0} chars)\n{1}", shortText.Length, shortText);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        private static string GetShortDescription(string s)
        {
            string sd = s;
            sd = sd.Substring(0, Math.Min(sd.Length, MAXIMUM_LENGTH_OF_THE_SHORT_DESCRIPTION));
            int lastDot = sd.LastIndexOf(".");
            int lastSpace = sd.LastIndexOf(" ");
            int lastChar = Math.Max(lastDot, lastSpace) + 1;
            if (lastChar == 0)
            {
                lastChar = sd.Length;
            }
            return sd.Substring(0, lastChar) + "...";
        }
    }
}

Result:

Long text (lenght:1162 chars)
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.

Short text (lenght:198 chars)
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci ...

Posted in C# by MdmSoft

If our work has been of help, you can help us with a small donation...
Our programmers will thank you!



All information contained in this web site are the property of MdmSoft. The information is provided "as is", MdmSoft will not be liable for any misuse of the code contained in these pages, nor can it be for inaccuracies, grammatical errors or other factors that may have caused damage or lost earnings. MdmSoft is not responsible for the content of comments posted by users.
The examples in this area have the educational and demonstration purposes only, and may be copied only for your reference, but cannot be used for commercial purposes, or for any other purpose, without the express written consent of MdmSoft.
MdmSoft also reserves the right to change, without notice, to your liking this web site, the pages and its sections, and may suspend temporarily or definitely the various services included on this site.
While using this site, you agree to have read and accepted our Terms of Service and Privacy Policy.