views:

31

answers:

3

Hello, i have a method which gets a string and a Hashtable ... the hash contains the char to be replaced in the key and the value which goes instead as value. Whats the best way to check the hash and replace the chars in the string?

Thanks :)

+2  A: 
foreach(var pair in hash)
{
    mystring = mystring.Replace(pair.Key, pair.Value);
}

If it really is a Hashtable and not a Dictionary<char, char> then you may need to cast the key and value to the correct type.

Alternatively depending on the number of items in your dictionary and the size of your string, it may be faster to iterate the string:

StringBuilder sb = new StringBuilder();
foreach (var char in mystring)
{
    char replace;
    if (hash.TryGetValue(char, out replace))
    {
        sb.Append(replace);
    }
    else
    {
        sb.Append(char);
    }
}
Simon Steele
So thats the most performant way?
grady
It depends :) The first method avoids lookups in the dictionary multiple times, but performs a string allocation for each replacement. The second will allocate far less, but at the expense of a lookup in the dictionary for each character in the string.
Simon Steele
In practice, unless you are worried about performance at this point I would go with the most succinct, understandable code.
Simon Steele
Its not so many items, maybe 10 ...
grady
Honestly, with small numbers like that, go for whichever code you prefer - it's highly unlikely you need to worry about performance with this. And the final answer with performance is that if you're really worried, then measure it - run both algorithms in a tight loop and measure the time taken, pick the best one. Just remember that it's not just speed but allocations that you need to look at.
Simon Steele
+1  A: 

You should loop through the string and use current char to get replace value from the hashtable. This will give you O(n) speed.

ika
A: 

What's about a littel lambda expression?

var t = new Dictionary<char, char>();
t.Add('T', 'B');
var s = "Test";
s = string.Concat(s.Select(c => { return t.ContainsKey(c) ? t[c] : c ; }));
Console.WriteLine(s);

Avoid the double lookup:

var t = new Dictionary<char, char>();
t.Add('T', 'B');
var s = "Test";
s = string.Concat(s.Select(c => 
    {
        char r;
        if(t.TryGetValue(c, out r))
            return r;
        else
            return c; 
    }));
d_schnell
Yup, that works, bear in mind that using ContainsKey means you are doing two dictionary lookups. While I believe in avoiding premature optimisation in general, it's good to get into good habits and this is a simple thing to avoid using TryGetValue.
Simon Steele