How do I truncate a .NET string?

Posted by Steve Guidi on Stack Overflow See other posts from Stack Overflow or by Steve Guidi
Published on 2010-05-05T20:50:01Z Indexed on 2010/05/05 20:58 UTC
Read the original article Hit count: 261

Filed under:
|
|
|

I apologize for such a question that likely has a trivial solution, but I strangely could not find a concise API for this problem.

Essentially, I would like to truncate a string such that it its length is not longer than a given value. I am writing to a database table and want to ensure that the values I write meet the constraint of the column's datatype.

For instance, it would be nice if I could write the following:

string NormalizeLength(string value, int maxLength)
{
    return value.Substring(0, maxLength);
}

Unfortunately, this raises an exception because maxLength exceeds the string boundaries. Of course, I could write a function like the following, but I was hoping that something like this already exists.

string NormalizeLength(string value, int maxLength)
{
    return value.Length <= maxLength ? value : value.Substring(0, maxLength);
} 

Where is the elusive API that performs this task? Is there one?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET