How can I truncate my strings with a "..." if they are too long?

Hope somebody has a good idea. I have strings like this:

abcdefg
abcde
abc

What I need is for them to be trucated to show like this if more than a specified lenght:

abc ..
abc ..
abc

Is there any simple C# code I can use for this?


Solution 1:

Here is the logic wrapped up in an extension method:

public static string Truncate(this string value, int maxChars)
{
    return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "...";
}

Usage:

var s = "abcdefg";

Console.WriteLine(s.Truncate(3));

Solution 2:

All very good answers, but to clean it up just a little, if your strings are sentences, don't break your string in the middle of a word.

private string TruncateForDisplay(this string value, int length)
{
  if (string.IsNullOrEmpty(value)) return string.Empty;
  var returnValue = value;
  if (value.Length > length)
  {
    var tmp = value.Substring(0, length) ;
    if (tmp.LastIndexOf(' ') > 0)
       returnValue = tmp.Substring(0, tmp.LastIndexOf(' ') ) + " ...";
  }                
  return returnValue;
}

Solution 3:

public string TruncString(string myStr, int THRESHOLD)
{
    if (myStr.Length > THRESHOLD)
        return myStr.Substring(0, THRESHOLD) + "...";
    return myStr;
}

Ignore the naming convention it's just in case he actually needs the THRESHOLD variable or if it's always the same size.

Alternatively

string res = (myStr.Length > THRESHOLD) ? myStr.Substring(0, THRESHOLD) + ".." : myStr;

Solution 4:

Here's a version that accounts for the length of the ellipses:

    public static string Truncate(this string value, int maxChars)
    {
        const string ellipses = "...";
        return value.Length <= maxChars ? value : value.Substring(0, maxChars - ellipses.Length) + ellipses;
    }