/// <summary>
/// Truncate a string to the specified length.
/// </summary>
/// <param name="value">The input string.</param>
/// <param name="length">The maximum length of the returned string.</param>
/// <returns>>A substring of the original, truncated to the specified length.</returns>
public static String Truncate(this String value, int length)
{
return value.Truncate(length, false);
}
/// <summary>
/// Truncate a string to the specified length.
/// </summary>
/// <param name="value">The input string.</param>
/// <param name="length">The maximum length of the returned string.</param>
/// <param name="addEllipsis">Specifies whether an ellipsis (...) is added to the end of the string.</param>
/// <returns>>A substring of the original, truncated to the specified length.</returns>
public static String Truncate(this String value, int length, bool addEllipsis)
{
// Return unchanged if no truncation required
if ((value == null) || (value.Length <= length) || (length <= 0))
{
return value;
}
// Ensure length meets conditions
if (addEllipsis && (length > 3))
{
length -= 3;
}
else
{
addEllipsis = false;
}
// Truncate based on passed length
String work = value.Substring(0, length);
// Optionally add ellipsis
return (addEllipsis ? (work + "...") : work);
}