【问题标题】:Iterate over array of strings and replace if exists迭代字符串数组并替换(如果存在)
【发布时间】:2013-12-02 04:14:38
【问题描述】:

我正在尝试遍历字符串数组并检查/替换输入字符串中是否存在任何字符串。使用 LINQ,这就是我目前所拥有的。

string input = "/main/dev.website.com"
string[] itemsToIgnore = { "dev.", "qa.", "/main/" };
string website = itemsToIgnore
                    .Select(x => 
                           { x = input.Replace(x, ""); return x; })
                    .FirstOrDefault();

当我运行它时,实际上什么都没有发生并且我的输入字符串保持不变?

【问题讨论】:

标签: c# arrays linq


【解决方案1】:
string website = itemsToIgnore
                   .Aggregate(input, (current, s) => 
                         current.StartsWith(s) ? current.Replace(s, string.Empty) : current);

并且没有 Linq

foreach (var part in itemsToIgnore) 
{
  if (website.StartsWith(part))
  {
    website = website.Replace(part, string.Empty);
  }
}

【讨论】:

  • 如何避免在“应该”之类的内容上使用替换匹配,我只想替换前面没有任何内容的完全匹配。
  • 你能举个例子解释一下你的愿望吗?
  • 如果我有字符串“应该”。注意到“。”在单词“should”之后,我的 itemsToIgnore 列表查找“d.”,它将替换字符串“should”。作为“应该”。如果 itemsToIgnore 列表前面没有任何内容,我只想用空字符串替换
  • 我已经对这个案例的答案进行了更改
  • 这样解决了我的问题,但又引发了另一个问题。如果我的 itemsToIgnore 列表等于 {"d.", "red."},并且我的输入是 "d.something.com",那么 StartsWith 命令将返回 false 并且不会替换它。为什么它忽略了我的第一个项目?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
  • 2017-07-03
  • 1970-01-01
相关资源
最近更新 更多