Samantha J T Star
Samantha J T Star

Reputation: 32758

Looking for a simple way to truncate a string in c#

I used the following:

t.Description.Substring(0, 20)

But there is a problem if there are less than 20 characters in the string. Is there a simple way (single inline function) that I could use to truncate to a maximum without getting errors when the string is less than 20 characters?

Upvotes: 3

Views: 1225

Answers (4)

Cheng Chen
Cheng Chen

Reputation: 43513

Another:

var result = new string(t.Description.Take(20).ToArray());

Upvotes: 0

Yahia
Yahia

Reputation: 70369

use

 string myShortenedText = ((t == null || t.Description == null) ? null : (t.Description.Length > maxL ? t.Description.Substring(0, maxL) : t));

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499810

How about:

t.Description.Substring(0, Math.Min(0, t.Description.Length));

Somewhat ugly, but would work. Alternatively, write an extension method:

public static string SafeSubstring(this string text, int maxLength)
{
    // TODO: Argument validation

    // If we're asked for more than we've got, we can just return the
    // original reference
    return text.Length > maxLength ? text.Substring(0, maxLength) : text;
}

Upvotes: 5

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

What about

t.Description.Take(20);

EDIT

Since the code above would infacr result in a char array, the proper code would be like this:

string.Join( "", t.Description.Take(20));

Upvotes: 2

Related Questions