Sunday, August 19, 2012

Limit string lengths in C# adding Ellipsis (...) text

The following snippet of code can be used to limit the lenth of strings in a paragraph of text using C#.

The code will add ellipsis (or '...') characters to the end of the string.

Happy coding

public static string Ellipsis(string originalText, int length)
        {
            if (originalText.Length <= length) return originalText;
            int pos = originalText.IndexOf(" ", length);
            if (pos >= 0)
                return originalText.Substring(0, pos) + "...";
            return originalText;
        }