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

Viewed 67393

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?

12 Answers

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;
}

I found this question after searching for "C# truncate ellipsis". Using various answers, I created my own solution with the following features:

  1. An extension method
  2. Add an ellipsis
  3. Make the ellipsis optional
  4. Validate that the string is not null or empty before attempting to truncate it.

    public static class StringExtensions
    {
        public static string Truncate(this string value, 
            int maxLength, 
            bool addEllipsis = false)
        {
            // Check for valid string before attempting to truncate
            if (string.IsNullOrEmpty(value)) return value;
    
            // Proceed with truncating
            var result = string.Empty;
            if (value.Length > maxLength)
            {
                result = value.Substring(0, maxLength);
                if (addEllipsis) result += "...";
            }
            else
            {
                result = value;
            }
    
            return result;
        }
    }
    

I hope this helps someone else.

I has this problem recently. I was storing a "status" message in a nvarcharMAX DB field which is 4000 characters. However my status messages were building up and hitting the exception.

But it wasn't a simple case of truncation as an arbitrary truncation would orphan part of a status message, so I really needed to "truncate" at a consistent part of the string.

I solved the problem by converting the string to a string array, removing the first element and then restoring to a string. Here is the code ("CurrentStatus" is the string holding the data)...

        if (CurrentStatus.Length >= 3750)
        {
            // perform some truncation to free up some space.

            // Lets get the status messages into an array for processing...
            // We use the period as the delimiter, then skip the first item and re-insert into an array.

            string[] statusArray = CurrentStatus.Split(new string[] { "." }, StringSplitOptions.None)
                                    .Skip(1).ToArray();

            // Next we return the data to a string and replace any escaped returns with proper one.
            CurrentStatus = (string.Join(".", statusArray))
                                    .Replace("\\r\\n", Environment.NewLine);


        }

Hope it helps someone out.

Refactor with new C# features just for disclosure:

// public static class StringExtensions { ...

private static string? Truncate(this string? value, int maxChars)
    =>
    string.IsNullOrEmpty(value) ? value :
    value.Length <= maxChars ? value :
    value[..maxChars] + "...";

Checked as "Community wiki", be free to improve answer.

Related