【问题标题】:Search string for Dictionary Value, then replace matched value with Dictionary's key?搜索字典值的字符串,然后用字典的键替换匹配的值?
【发布时间】:2020-08-04 19:05:51
【问题描述】:

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

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




【问题讨论】:

    标签: c# .net string dictionary


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        我们可以先找到键值对,替换成:

        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;(如果不存在)

        【讨论】:

          猜你喜欢
          • 2018-09-11
          • 2020-08-27
          • 2022-01-15
          • 2017-07-15
          • 1970-01-01
          • 2018-01-02
          • 1970-01-01
          • 1970-01-01
          • 2018-11-24
          相关资源
          最近更新 更多