Skip to content

Instantly share code, notes, and snippets.

@craigtp
Created February 1, 2016 15:06
Show Gist options
  • Save craigtp/e98e5c61520f4d94abcf to your computer and use it in GitHub Desktop.
Save craigtp/e98e5c61520f4d94abcf to your computer and use it in GitHub Desktop.
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