Skip to content

Instantly share code, notes, and snippets.

@timiles
Last active October 6, 2015 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timiles/2936923 to your computer and use it in GitHub Desktop.
Save timiles/2936923 to your computer and use it in GitHub Desktop.
String helper: Truncate with ellipsis
public static string Truncate(this string s, int maxLength, bool withEllipsis = false)
{
if (maxLength < 0) throw new ArgumentOutOfRangeException(nameof(maxLength), "must be at least zero");
if (s == null || s.Length <= maxLength) return s;
if (withEllipsis && maxLength > 3)
{
return s.Substring(0, maxLength - 3) + "...";
}
return s.Substring(0, maxLength);
}
//[Test]
//public void TruncateTests()
//{
// Assert.IsNull((null as string).Truncate(10));
// Assert.Throws<ArgumentOutOfRangeException>(() => "blah".Truncate(-1));
// Assert.AreEqual("", "blah".Truncate(0));
// Assert.AreEqual("", "blah".Truncate(0, withEllipsis: true));
// Assert.AreEqual("b", "blah".Truncate(1));
// Assert.AreEqual("b", "blah".Truncate(1, withEllipsis: true));
// Assert.AreEqual("bl", "blah".Truncate(2));
// Assert.AreEqual("bl", "blah".Truncate(2, withEllipsis: true));
// Assert.AreEqual("bla", "blah".Truncate(3));
// Assert.AreEqual("bla", "blah".Truncate(3, withEllipsis: true));
// Assert.AreEqual("blah", "blah".Truncate(4));
// Assert.AreEqual("blah", "blah".Truncate(4, withEllipsis: true));
// Assert.AreEqual("blah", "blah".Truncate(5));
// Assert.AreEqual("blah", "blah".Truncate(5, withEllipsis: true));
// Assert.AreEqual("blah", "blahsdvsdv".Truncate(4));
// Assert.AreEqual("b...", "blahsdvsdv".Truncate(4, withEllipsis: true));
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment