If you’re like me who don’t like to display all the contents of my item’s description (not efficient if length is more than 5000 words) in a full blast on every record that I have on my database, by having the function sitting as an extension method, I can easily call this method to truncate or limit the display of that description to a specified given length and the truncated string will then be replaced by a “…”
Here’s the code of how I create it:
1: public static class StringEx
2: {
3: /// <summary>
4: /// Truncates the string to a specified length and replace the truncated to a ...
5: /// </summary>
6: /// <param name="text">string that will be truncated</param>
7: /// <param name="maxLength">total length of characters to maintain before the truncate happens</param>
8: /// <returns>truncated string</returns>
9: public static string Truncate(this string text, int maxLength)
10: {
11: // replaces the truncated string to a ...
12: const string suffix = "...";
13: string truncatedString = text;
14:
15: if (maxLength <= 0) return truncatedString;
16: int strLength = maxLength - suffix.Length;
17:
18: if (strLength <= 0) return truncatedString;
19:
20: if (text == null || text.Length <= maxLength) return truncatedString;
21:
22: truncatedString = text.Substring(0, strLength);
23: truncatedString = truncatedString.TrimEnd();
24: truncatedString += suffix;
25: return truncatedString;
26: }
27: }
and applying the code above like this:
1: string newText = "this is the palce i want to be, Cindys is the place to be!";
2: Console.WriteLine("New Text: {0}", newText.Truncate(40));
I already posted this on Extension Method site.