23

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • 4
    Check the length of the string, and if it's greater than 20 characters truncate, otherwise leave it as is. – Tim Jun 22 '13 at 10:20

5 Answers5

43

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);
Decius
  • 155
  • 3
  • 11
Zbigniew
  • 27,184
  • 6
  • 59
  • 66
  • Maybe also checking for `null` in the extension method? – Uwe Keim Jun 22 '13 at 10:26
  • 1
    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 Jun 22 '13 at 10:32
  • @Chris Yes, this is indeed much better name for this method :) Thank you – Zbigniew Jun 22 '13 at 10:34
  • 1
    length also could be optional parameter. – adt Jun 22 '13 at 10:39
  • @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? – Zbigniew Jun 22 '13 at 10:42
18

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)]
AgentFire
  • 8,944
  • 8
  • 43
  • 90
9
string title = new string(LongTitle.Take(20).ToArray());
cuongle
  • 74,024
  • 28
  • 151
  • 206
  • 5
    Note this is quite inefficient since it create an intermediate char array which is then immediately copied and discarded. – Lee Jun 22 '13 at 10:26
  • 2
    @Lee: You are right, but with small string, it's trivial – cuongle Jun 22 '13 at 10:32
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));
Peter Rasmussen
  • 16,474
  • 7
  • 46
  • 63
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;
Sebastian
  • 5,177
  • 4
  • 30
  • 47