Create a gist now

Instantly share code, notes, and snippets.

public static class StringExtentionMethods
{
public static string TruncateAtWord(this string input, int maxlength, bool addEllipsis)
{
if (input == null || input.Length <= maxlength) return input;
var ellipsisLengthDeduction = (addEllipsis ? 3 : 0);
var iLastSpace = input.LastIndexOf(" ", (maxlength - ellipsisLengthDeduction), StringComparison.Ordinal);
var iLength = 0;
if (iLastSpace < 0)
{
// There are no spaces in this string, so we just truncate based on the overall length and take into account whether or not
// we're going to be adding ellipsis to the result.
iLength = maxlength - ellipsisLengthDeduction;
}
else
{
// There are spaces in the string, so we use the position of the last space as the place to cut the string.
// Whether or not we're adding Ellipsis to the string is already accounted for when calculating the last space position.
iLength = iLastSpace;
}
return string.Format("{0}{1}", input.Substring(0, iLength), (addEllipsis ? "..." : ""));
}
public static bool Contains(this string source, string value, StringComparison comparisonType)
{
return source.IndexOf(value, comparisonType) >= 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment