Melony Melony - 20 days ago 7
C# Question

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


Possible Duplicate:

indicate truncation in ToolTipStatusLabel automatically




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?

Answer

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