5

What useful helpers for String manipulation to you have to share?

I once wrote a replacement for String.Format(), which I find much more neat to use:

public static class StringHelpers
{
    public static string Args(this string str, object arg0)
    {
        return String.Format(str, arg0);
    }

    public static string Args(this string str, object arg0, object arg1)
    {
        return String.Format(str, arg0, arg1);
    }

    public static string Args(this string str, object arg0, object arg1, object arg2)
    {
        return String.Format(str, arg0, arg1, arg2);
    }

    public static string Args(this string str, params object[] args)
    {
        return String.Format(str, args);
    }
}

Example:

// instead of String.Format("Hello {0}", name) use:
"Hello {0}".Args(name)

What other useful helpers do you have for strings in C#?

Andy
  • 2,670
  • 3
  • 30
  • 49
  • I'm not using any. Yours looks cool. – TarasB Dec 12 '10 at 08:10
  • It's usually a good idea to include a CultureInfo object with String.Format. You could include a default CultureInfo in your extension method. – Jason Down Dec 12 '10 at 09:17
  • A related example you might find interesting: http://stackoverflow.com/questions/1322037/how-can-i-create-a-more-user-friendly-string-format-syntax/1322103#1322103 – Marc Gravell Dec 12 '10 at 09:31

1 Answers1

4

A fairly popular one that is more of a convenience extension method is the following:

public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string s)
    {
        return String.IsNullOrEmpty(s);
    }
}

Nothing great, but writing myString.IsNullOrEmpty() is more convenient than String.IsNullOrEmpty(myString).

Jason Down
  • 21,731
  • 12
  • 83
  • 117
  • I use to do this, but then in retrospect decided to remove it because you could be calling a method on a null. – Yuriy Faktorovich Dec 12 '10 at 09:00
  • While it's true that this one is popular (and I do use it often... probably mostly out of laziness), I am not really a fan of it. There are some good arguments against it in this post: http://stackoverflow.com/questions/790810/is-extending-string-class-with-isnullorempty-confusing – Jason Down Dec 12 '10 at 09:20