搜索字典值的字符串,然后将匹配的值替换为字典的键?



所以我有一个字典,里面有Keys,它们是地址缩写的缩写版本(这是我在字典中的值(。我需要搜索一个字符串,看看它是否包含字典中的值,然后用字典中的键值替换字符串中匹配的值。例如:

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


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

如果在字典中找到所有字符串,您可能希望用它们的对应字符串替换它们。这可以在一个简单的循环中完成:

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

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

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

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

最新更新