Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

A better tr

Name: Anonymous 2010-08-22 14:39

private static readonly HashSet<char> badChars =
    new HashSet<char> { '!', '@', '#', '$', '%', '_' };

public static string CleanString(this string str)
{
    var result = new StringBuilder(str.Length);
    for (int i = 0; i < str.Length; i++)
    {
        if (!badChars.Contains(str[i]))
            result.Append(str[i]);
    }
    return result.ToString();
}


This algorithm makes use of the .NET 3.5 'HashSet' class to give O(1) look up time for detecting a bad char. This makes the overall algorithm O(n) rather than the O(nm) of your posted one (m being the number of bad chars); it also is lot a better with memory usage, as explained above.

Name: Anonymous 2010-08-22 19:07

>>2
Well, not with Unicode. That said it is a nice solution and reminds me of something I read the other day[1]

>>8
How so? It just looks like memoisation to me, and I'd hope that was part of any functional programmers toolbelt[2].

--
1. http://jaspervdj.be/posts/2010-07-11-the-dwarfs-and-the-fast-marking-algorithm.html I was suckered in by the title thinking it was something else
2. This assumes that the people on /prog/ who claim to prefer functional programming actually do it, and don't just spend all day jerking it to loeb.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List