Thursday, 4 September 2008

Triming strings to whole words in C#

This is a method that I have found useful whilst having to trim a string to a number of chars, whilst keeping whole words.

public string TrimToNumberOfChars (string originalString, int maxChar)
if (originalString.Length <= maxChar)
return originalString;

int lastSpace = originalString.LastIndexOf(" ", maxChar - 1);
if (lastSpace == -1) return "";
return originalString.Substring(0, lastSpace) + "...";

I hope other people find this useful.

No comments: