Truncate string on whole words in .NET C#

Try the following. It is pretty rudimentary. Just finds the first space starting at the desired length.

public static string TruncateAtWord(this string value, int length) {
    if (value == null || value.Length < length || value.IndexOf(" ", length) == -1)
        return value;

    return value.Substring(0, value.IndexOf(" ", length));
}

Leave a Comment