A while back I needed a routine which would display the first few hundred characters of a longer chunk of text. Obviously, it's easy enough to do that with the Substring method of a string. However, I wanted to do this on a word boundary (I didn't want to end up with half of the word being displayed). So I wrote a simple routine which broke up the string into an array (using Split()), then rebuilt the string (keeping track of the length along the way). Maybe 25 lines or code or so. It seemed to work OK, so I was good to go.

The other day I realized I needed to adjust the code to strip out HTML markup before displaying the text - you can imagine how "nice" that might look if I happened to chop off an ending tag somewhere. I knew I had a third party library to do this; there are a lot of really useful little routines hiding in the West Wind Web Store .NET 2.0. So I took a look through the library and found what I was looking for. While looking for it, I noticed another routine which appeared to do exactly the same thing I wanted. Except it was like 5 lines and much easier to understand. Doh!

30 seconds later I rewrote my routine. Here it is...

        public static string TruncateString(string source, int maxLength, string ending)
        {
            // Do we even have to truncate it?

            if (source.Length <= maxLength)
                return source;

            string text = source.Substring(0, maxLength);

            text = text.Substring(0, text.LastIndexOf(" ")); 

            return text;
        }


 
Comments are closed.