views:

326

answers:

5

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

Essentially, 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?

+4  A: 

I always use the ?: solution, I have not found another way.

Jedi Master Spooky
+17  A: 

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 )
  {
      return value.Length <= maxLength ? value : value.Substring(0, maxLength); 
  }
}

// now we can write:
var someString = "...";
someString = someString.Truncate( 2 );
LBushkin
Great Solution, but remembered this only works in NET 3.5 and Up. Don't try it in NET2.0.
Jedi Master Spooky
As long as you're in VS 2008, and presumably VS 2010, you could still do this even if targeting .Net 2.0. http://www.danielmoth.com/Blog/Using-Extension-Methods-In-Fx-20-Projects.aspx
Mark
You really should add a null check for the sake of completeness.
ChaosPandion
A: 

There is nothing in .net for this that I am aware of - here is my version which adds "...":

public static string truncateString(string originalString, int length) {
  if (string.IsNullOrEmpty(originalString)) {
   return originalString;
  }
  if (originalString.Length > length) {
   return originalString.Substring(0, length) + "...";
  }
  else {
   return originalString;
  }
}
Ray
+7  A: 

Or instead of the ternary operator, you could use Math.min

public static class StringExt
{
    public static string Truncate( this string value, int maxLength )
    {
        if (string.isNullOrEmpty(value)) { return value; }

        return value.Substring(0, Math.Min(value.length, maxLength));
    }
}
Chad
Clever! And the following expression is optimized to return a reference to the original string: `value.Substring(0, value.Length)`.
Steve Guidi
A: 

You could use LINQ... it eliminates the need to check string length. Admittedly maybe not the most efficient, but it's fun.

string result = string.Join("", value.Take(maxLength)); // .NET 4 Join

or

string result = new string(value.Take(maxLength).ToArray());
tames