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.开发者_StackOverflow社区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#?
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)
.
精彩评论