0

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) + "...";
}
7
  • The Truncate class is not part of the .NET framework. I'd recommend talking to whoever wrote the TruncateString method. Commented Nov 22, 2013 at 20:37
  • Could you show the code of TruncateString? Commented Nov 22, 2013 at 20:37
  • 1
    Why a custom class? _longString.Substring(0, 299).Trim() will do what you want. Commented Nov 22, 2013 at 20:42
  • 1
    Can somebody please explain me how value.SubString(0, maxChars) + "..." will end with spaces? And how can it be longer than maxChars + 3 characters? Commented Nov 22, 2013 at 20:54
  • There are thousands of right examples of Truncate for a string. (Example) This one fails if the string has more than 300 chars in length because the string returned is 303 chars Commented Nov 22, 2013 at 20:55

1 Answer 1

2

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() + "...";
}
Sign up to request clarification or add additional context in comments.

7 Comments

This will trim the end white spaces before the custom class shortens it, so if the center of the string has a substring of white spaces he still will have the problem.
@ENC0D3D to make this work do the Trim() on the string after the custom class shortens it.
Thanks! That worked! Hmm....Now if SO would give split points awards this would benefit both of you.
@ENC0D3D thanks but I really don't care about the points on these pages, the learning is fun in itself.
Please correct me if I am wrong. But in case of a long string TruncateString returns a string that ends with ..., right? What will the call to Trim() do?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.