Monday, May 7, 2012

C# Truncate String - Whole Words

This is an update to my original string truncate helper which can be set to respect whitespace when terminating a string. This version will start at the character index specified as max length and then iterate back to the first instance of whitespace (if it exists), thus keeping whole words intact.

public static string Truncate(this string str, int maxLength, bool onlyOnWhiteSpace = false, bool appendEllipses = false) {
    if (str == null || maxLength >= str.Length)
    {
        return str;
    }

    if (onlyOnWhiteSpace
        && !char.IsWhiteSpace(str[maxLength])
        && str.Substring(0, maxLength).Any(char.IsWhiteSpace))
    {
        for (; maxLength >= 0; maxLength--)
        {
            if (char.IsWhiteSpace(str[maxLength]))
            {
                break;
            }
        }
    }

    return str.Substring(0, maxLength) + (appendEllipses ? "..." : "");
}

No comments: