在字符串中搜索“字典值”,然后用“字典的键”替换匹配的值?

时间:2020-04-21 21:32:18

标签: c# .net string dictionary

因此,我有一本词典,其中包含键,这些键是地址缩写的缩写版本(这是我在本词典中的值)。我需要在字典中搜索字符串是否包含值,然后用字典中的键值替换字符串中匹配的值。 例如:

Dictionary<string, string> addresses = new Dictionary<string, string>(){{"BLVD","BOULEVARD"}};
var address = "405 DAVIS BOULEVARD";

所以在上面的示例中,我想找到“ BOULEVARD”作为匹配项,然后将其替换为“ BLVD”。因此,新地址将为“ 405 DAVIS BLVD”。 到目前为止,下面的代码是我所拥有的,但是我不确定如何使用适当的键值完成它的替换部分。任何提示将不胜感激,谢谢!

foreach(var value in addresses.Values)
{
     if(address.ToUpper().Contains(value))
     {
         //this is where i get stuck with how to replace with the appropriate key of the dictionary
     }
}




3 个答案:

答案 0 :(得分:1)

最简单的解决方案是反转您的关键和价值, Dictionary<string, string> addresses = new Dictionary<string, string>(){"BOULEVARD","BLVD"}; 然后,您只需查找密钥即可替换: address = address.Replace(key, addresses[key]);

答案 1 :(得分:0)

我们可以先找到键值对,然后使用替换:

Dictionary<string, string> addresses = new Dictionary<string, string>() { { "BLVD", "BOULEVARD" } };
var address = "405 DAVIS BOULEVARD";

KeyValuePair<string,string> keyValue =
    addresses.FirstOrDefault((x) => address.ToUpper().Contains(x.Value));

if(keyValue.Value != null)
{
    address = address.ToUpper().Replace(keyValue.Value, keyValue.Key);
}

注意:请为扩展方法using System.Linq;添加FirstOrDefault(如果不存在)

答案 2 :(得分:0)

假设您想将所有字符串(如果在字典中找到)替换为对应的字符串。这可以通过一个简单的循环来完成:

Dictionary<string, string> addresses = new Dictionary<string, string>() 
    { { "BLVD", "BOULEVARD" } };

var address = "405 DAVIS BOULEVARD";

// Replace all 'Value' items found with the 'Key' string
foreach(var item in addresses)
{
    address.Replace(item.Value, item.Key);
}

如果您要执行不区分大小写的替换,RegEx也是一个不错的选择:

foreach(var item in addresses)
{
    address = Regex.Replace(address, item.Value, item.Key, RegexOptions.IgnoreCase);
}