Friday, October 3, 2008

Fabulous Adventures in Reading

So on my new favoritest site ever for the week StackOverflow someone asked if this could be done in C#:
$patterns[0] = '/=C0/';
$patterns[1] = '/=E9/';
$patterns[2] = '/=C9/';


$replacements[0] = 'à';
$replacements[1] = 'é';
$replacements[2] = 'é';
return preg_replace($patterns, $replacements, $text);
I thought this could be an interesting challenge with Linq. And all things can be solved with Linq. Also, this post provides a valuable moral at the end.

So what the hell is that? Basically the idea is to take in some text, you know the stuff you send to people on your phone, and replace one set of characters with another. Make sense talk: TAKE TEXT! SMASH BAD THINGS! PUT GOOD THINGS IN!
String text;
List<Char> patternsToReplace;
List<Char> patternsToUse;

patternsToReplace = new List<Char>();
patternsToReplace.Add('a');
patternsToReplace.Add('c');
patternsToUse = new List<Char>();
patternsToUse.Add('X');
patternsToUse.Add('Z');

text = "This is a thing to replace stuff with";

var allAsAndCs = text.ToCharArray()
               .Select
               (
                 currentItem => patternsToReplace.Contains(currentItem)
                   ? patternsToUse[patternsToReplace.IndexOf(currentItem)]
                   : currentItem
               )
               .ToArray();
        
text = new String(allAsAndCs);
It's actually very simple. First convert the text into a character array. Then select through them one by one. If the list of ones to be replaced (patternsToReplace) just happens to have the current character, replace it with the corresponding one from the replacements (patternsToUse) otherwise just return the original.

Now the annoying thing about this example is that in preg_replace the two lists have no real correlation. It just assumes you want and index to index match. Therefore patternsToUse[0] replaces patternsToReplace[0]. But hey, I didn't invent the thing.

Another note is that instead of using Char[] I used List<Char> because arrays don't have index of and it saves the one step of charArray.ToList().IndexOf. I'm lazy and I like lists.

Now for the moral of the story:

'Course I dove right into Linq and responded... not reading that he/she needed a 2.0 solution and ultimately gave the client NOTHING THAT HE/SHE WANTED. So, if you take anything from this... and you probably won't... Always read the requirements first.

using System;
using System.Collections.Generic;
using System.Linq;

No comments: