25

I tried the following:

var Title = LongTitle.Substring(0,20) 

This works but not if LongTitle has a length of less than 20. How can I limit strings to a maximum of 20 characters but not get an error if they are just for example 5 characters long?

1
  • 4
    Check the length of the string, and if it's greater than 20 characters truncate, otherwise leave it as is. Commented Jun 22, 2013 at 10:20

5 Answers 5

45

Make sure that length won't exceed LongTitle (null checking skipped):

int maxLength = Math.Min(LongTitle.Length, 20); string title = LongTitle.Substring(0, maxLength); 

This can be turned into extension method:

public static class StringExtensions { /// <summary> /// Truncates string so that it is no longer than the specified number of characters. /// </summary> /// <param name="str">String to truncate.</param> /// <param name="length">Maximum string length.</param> /// <returns>Original string or a truncated one if the original was too long.</returns> public static string Truncate(this string str, int length) { if(length < 0) { throw new ArgumentOutOfRangeException(nameof(length), "Length must be >= 0"); } if (str == null) { return null; } int maxLength = Math.Min(str.Length, length); return str.Substring(0, maxLength); } } 

Which can be used as:

string title = LongTitle.Truncate(20); 
Sign up to request clarification or add additional context in comments.

5 Comments

Maybe also checking for null in the extension method?
I too have used an extension method for this, but out of respect for others who maintain my code (and for the sake of brevity), might I suggest a more apt method signature: Truncate(int maxLength)
@Chris Yes, this is indeed much better name for this method :) Thank you
length also could be optional parameter.
@adt You're free to do whatever you like with this method. length could be optional, but what value would it take? 0? Does it even makes sanse to truncate string to empty string?
19

Shortest, the:

var title = longTitle.Substring(0, Math.Min(20, longTitle.Length)) 

Update

Ok since some new C# version this suggested variant became the shortest:

var title = longTitle[..Math.Min(20, longTitle.Length)] 

1 Comment

Shorter: var Title = longTitle[..Math.Min(20, longTitle.Length)]
10
string title = new string(LongTitle.Take(20).ToArray()); 

2 Comments

Note this is quite inefficient since it create an intermediate char array which is then immediately copied and discarded.
@Lee: You are right, but with small string, it's trivial
5

If the string Length is bigger than 20, use 20, else use the Length.

string title = LongTitle.Substring(0, (LongTitle.Length > 20 ? 20 : LongTitle.Length)); 

1 Comment

Learn to use Math.Min for this purpose.
3

You can use the StringLength attribute. That way no string can be stored that is longer (or shorter) than a specified length.

See: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.stringlengthattribute%28v=vs.100%29.aspx

[StringLength(20, ErrorMessage = "Your Message")] public string LongTitle; 

Comments