简体   繁体   English

从Hashtable中替换字符串中的字符的最佳方法?

[英]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 replaced in the key and the value which goes instead as value. 我有一个获取字符串和Hashtable的方法...哈希包含要在键中替换的char以及值作为值的值。 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. 如果它确实是Hashtable而不是Dictionary<char, char>那么您可能需要将键和值强制转换为正确的类型。

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. 您应该遍历字符串并使用当前char来从哈希表中获取替换值。 This will give you O(n) speed. 这将给你O(n)速度。

What's about a littel lambda expression? 什么是一个小小的lambda表达?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM