I would like to truncate a string such that 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
generally exceeds the boundaries of the string value
. 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?
There isn't a
Truncate()
method on string, unfortunately. You have to write this kind of logic yourself. What you can do, however, is wrap this in an extension method so you don't have to duplicate it everywhere:Now we can write:
The .NET Framework has an API to truncate a string like this:
But in a C# app you'll probably prefer to roll your own than taking a dependency on Microsoft.VisualBasic.dll, whose main raison d'etre is backwards compatibility.
I know this is an old question, but here is a nice solution:
Returns: hello...
This is the code I usually use:
TruncateString
I'd Recommend using the substring method for the same effective functionality.
This has the benefit of letting you splice your string from either side or even somewhere in the middle without writing additional methods. Hope that helps :)
For additional reference: https://www.dotnetperls.com/substring