Reputation: 503
I'm trying to limit the number of characters in a string.
However when I try the following:
Truncate.TruncateString(_longString, 300);
I Still get spaces included beyond 300 characters. Is there an alternative so that spaces are counted within the character limit?
public static string TruncateString (this string value, int maxChars)
{
return value.Length <= maxChars ? value : value.SubString(0, maxChars) + "...";
}
Upvotes: 0
Views: 881
Reputation: 25053
If you don't need the trailing spaces (and often you don't), you can always do this:
Truncate.TruncateString(_longstring, 300).Trim();
Edit
Although this answer was accepted as correct, the right way is actually to leave the Trim()
out of the above statement and instead to put it here:
public static string TruncateString (this string value, int maxChars)
{
value = value.trim();
return value.Length <= maxChars ? value : value.SubString(0, maxChars).Trim() + "...";
}
Upvotes: 2