Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I truncate a .NET string?

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?

like image 541
Steve Guidi Avatar asked May 05 '10 20:05

Steve Guidi


People also ask

How do you truncate a string in C#?

Substring() method in C#. Then we created the extension method Truncate() that takes the desired length and truncates the string to the desired length. If the string variable is null or empty, the Truncate() method returns the string.

What does TRIM () do in C#?

The Trim() method in C# is used to return a new string in which all leading and trailing occurrences of a set of specified characters from the current string are removed.


1 Answers

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:

public static class StringExt {     public static string Truncate(this string value, int maxLength)     {         if (string.IsNullOrEmpty(value)) return value;         return value.Length <= maxLength ? value : value.Substring(0, maxLength);      } } 

Now we can write:

var someString = "..."; someString = someString.Truncate(2); 
2021-09-17 Alternative with suffix and c#8 nullable reference types.
public static class StringExt {     public static string? Truncate(this string? value, int maxLength, string truncationSuffix = "…")     {         return value?.Length > maxLength             ? value.Substring(0, maxLength) + truncationSuffix             : value;     } } 

To write:

"abc".Truncate(2);          // "ab…" "abc".Truncate(3);          // "abc" ((string)null).Truncate(3); // null 
like image 186
LBushkin Avatar answered Sep 18 '22 01:09

LBushkin