Deal with it or don't
Obvious Extension Method: Left for strings… with Ellipsis!
Substring() is fun, right? It’s fun because “Index and length must refer to a location within the string.”
Well, sometimes, you just want the Left few characters. Sometimes, if you chop of the extra length in your string, you want ellipsis to indicate there are missing pieces.
Here you go:
- public static class StringExtensions
- public static string Left(this string value,
- int length,
- OverflowBehavior overflowBehavior = OverflowBehavior.None)
- var substring = value.Substring(0, Math.Min(length, value.Length));
- return (overflowBehavior == OverflowBehavior.Ellipsis &&
- length < value.Length) ? substring + “…” : substring;
- public enum OverflowBehavior
Now, you can use it like so:
“I’m just saying bless your heart.”.Left(14, OverflowBehavior.Ellipsis) will return “I’m just sayin…”
It defaults to ‘None’, so you can just do “I’m just saying bless your heart.”.Left(14) and get “I’m just sayin”