Last active
October 6, 2015 04:28
-
-
Save timiles/2936923 to your computer and use it in GitHub Desktop.
String helper: Truncate with ellipsis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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