Truncate string on whole words in .NET C#

TimS picture TimS · Oct 23, 2009 · Viewed 47.9k times · Source

I am trying to truncate some long text in C#, but I don't want my string to be cut off part way through a word. Does anyone have a function that I can use to truncate my string at the end of a word?

E.g:

"This was a long string..."

Not:

"This was a long st..."

Answer

Dave picture Dave · Oct 23, 2009

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));
}