Thursday, August 12, 2010

Some new extension methods for System.String

So AdamSpeight2008 posted a small challenge for the VB.NET section, and it got me thinking. That would be a pretty useful extension method. I'd previously written a RemoveMany extension for strings, might as well add a ReplaceMany. Also, I'll throw in a ToTitleCase for free.

So, here they are:
public static class Extensions
{
    public static string ReplaceMany(this string dirty, Dictionary<char, char> replacer)
    {
        StringBuilder sb = new StringBuilder();
        dirty.ToList().ForEach(x => sb.Append(replacer.ContainsKey(x) 
            ? replacer[x] 
            : x));
        return sb.ToString();
    }

    public static string ReplaceMany(this string dirty, params Tuple<char, char>[] pairs)
    {
        StringBuilder sb = new StringBuilder();
        dirty.ToList().ForEach(x => sb.Append(pairs.Any(y => y.Item1 == x) 
            ? pairs.First(y => y.Item1 == x).Item2 
            : x));
        return sb.ToString();
    }

    public static string ReplaceMany(this string dirty, params Tuple<string, string>[] pairs)
    {
        pairs.ToList().ForEach(x => dirty = dirty.Replace(x.Item1, x.Item2));
        return dirty;
    }

    public static string RemoveMany(this string dirtyString, params string[] stringsToRemove)
    {
        return dirtyString.Split(stringsToRemove, StringSplitOptions.None)
            .Aggregate((sentence, next) => sentence + next);
    }

    public static string ToTitleCase(this string sentence)
    {
        return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(sentence);
    }
}


Note that the ReplaceMany uses a Dictionary, which I'm not exactly thrilled about, but off the top of my head I can't think of any easy and elegant way to do things differently. Maybe tuples.

Definitely tuples. I've added an overload that takes tuples of chars, and tuples of strings.

Here's some code to test them and show usage, if you're interested.
Dictionary<char, char> dict = 
    new Dictionary<char, char>() { { 'D', 'a' }, { 'a', 'D' }, { ' ', 'X' } };
Console.WriteLine("Dream In Code".ReplaceMany(dict));
Console.WriteLine("Bytes.com".ReplaceMany(Tuple.Create('B', 'c'),
    Tuple.Create('c', 'B'), Tuple.Create('.', 'U')));
Console.WriteLine("Bob is not your old uncle".ReplaceMany(Tuple.Create("not", "surely"),
    Tuple.Create("old", "young")));
Console.WriteLine("Texstying".RemoveMany("x", "y"));
Console.WriteLine("this sHould be in title caSE".ToTitleCase());
Console.ReadKey();

No comments:

Post a Comment

Speak your mind.