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:

  1. public static class StringExtensions
  2. {
  3.   public static string Left(this string value,
  4.               int length,
  5.               OverflowBehavior overflowBehavior = OverflowBehavior.None)
  6.   {
  7.     var substring = value.Substring(0, Math.Min(length, value.Length));
  8.     return (overflowBehavior == OverflowBehavior.Ellipsis &&
  9.             length < value.Length) ? substring + “…” : substring;
  10.   }
  11. }
  12. public enum OverflowBehavior
  13. {
  14.   None,
  15.   Ellipsis
  16. }

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”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: