views:

2060

answers:

4

Hi,

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..."

Thanks, Tim

+13  A: 

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.SubStr(0, value.IndexOf(" ", length));
}
Dave
Perfect! And not a regex in sight :)
TimS
It might make sense to find the first space BEFORE the desired length? Otherwise, you have to guess at what the desired length?
mlsteeves
Also should be -1 for not using regex ;)
Goran
@mlseeves Good point but I'm not too worried in this instance, as this is just a vanity function, so there is no fixed length cut off.
TimS
The `@string` usage is uncalled-for: it's unnecessary and confusing in this instance. The parameter could as easily have been named `str`. If not for that, I would have upvoted this answer.
LBushkin
Or the recommended 'value'.
sixlettervariables
+3  A: 

If you are using windows forms, in the Graphics.DrawString method, there is an option in StringFormat to specify if the string should be truncated, if it does not fit into the area specified. This will handle adding the ellipsis as necessary.

http://msdn.microsoft.com/en-us/library/system.drawing.stringtrimming.aspx

mlsteeves
This is for an ASP.Net page, but I do some Win Forms stuff so good to know!
TimS
+6  A: 

Thanks for your answer Dave. I've tweaked the function a bit and this is what I'm using ... unless there are any more comments ;)

public static string TruncateAtWord(this string input, int length)
{
    if (input == null || input.Length < length)
        return input;
    int iNextSpace = input.LastIndexOf(" ", length);
    return string.Format("{0}...", input.Substring(0, (iNextSpace > 0) ? iNextSpace : length).Trim());
}
TimS
Further to this, I am also now calling another string utility function from within this one, which strips out any HTML tags (using RegEx). This minimises the risk of broken HTML as a result of truncation, as all string will be in plain text.
TimS
Note that this method looks for the first space *AFTER* the specified length value, almost always causing the resulting string to be longer than the value.To find the last space prior to length, simply substitute `input.LastIndexOf(" ", length)` when calculating `iNextSpace`.
CBono
+100 for CBono's comment - this needs to be before! In the eventofareallylongwordlikethisoneyouwillhaveaverylongstringthatisfarbeyondyourdesiredlength!
Jason