Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 588
Samantha J T Star Avatar asked Nov 26 '25 13:11

Samantha J T Star


1 Answers

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;
}
like image 52
Jon Skeet Avatar answered Nov 29 '25 04:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!