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); } }
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.