开发者

Best way to replace chars in a string from a Hashtable?

i have a method which gets a string and a Hashtable ... the hash contains the char to be repla开发者_如何学运维ced 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 :)


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜