【问题标题】:Replace a string with each string in a list用列表中的每个字符串替换一个字符串
【发布时间】:2021-10-19 16:45:09
【问题描述】:

我有一个这样的列表:

List<string> _unWantedWords = new List<string> { "word1", "word2", "word3" };

我有一个这样的字符串:

string input = "word1mdjw ksjcword2 d word3fjwu";

我想删除输入字符串中不需要的单词,但字符串在 C# 中是不可变的,所以我想用 lambda 表达式一口气做一些花哨的事情。像这样:

string output = _unWantedWords.Select(x => input.Replace(x, ""));

但我似乎无法让它工作,有什么想法吗? :)

丹尼尔

【问题讨论】:

  • 如果列表足够长,请考虑使用StringBuilder.Replace 而不是String.Replace。它不像字符串操作那样通过垃圾处理

标签: c# string list


【解决方案1】:

一般情况任务存在细微问题:

我们应该递归地吗?

 "woword1rd1ABC" -> "word1ABC" -> ABC
    |   |            |   |
    remove        remove again

移除的顺序是什么?如果我们要删除{"ab", "bac"},那么"XabacY" 的期望结果是什么?

 "XabacY" -> "XacY" // ab removed
          -> "XaY"  // bac removed

在最简单的情况下(按照它们出现在_unWantedWords 中的顺序删除单词,没有递归)你可以放(让我们使用Linq,因为你已经尝试过@987654326 @):

 input = _unWantedWords.Aggregate(input, (s, w) => s.Replace(w, ""));        

我们无法更改string 本身,但我们可以更改引用(即分配给input

【讨论】:

  • "input = _unWantedWords.Aggregate(input, (s, w) => s.Replace(w, ""));"为我的情况做了,因为这些词只需要按照它们出现的顺序删除。感谢您的回复:) 丹尼尔
【解决方案2】:

您可以改用ForEach

_unWantedWords.ForEach(x => { input= input.Replace(x, "")});

【讨论】:

    【解决方案3】:

    您可以使用 ForEach 函数来替换输入中的文本。

    string output = input;
    _unWantedWords.ForEach(x => output = output.Replace(x, ""));
    

    您可以创建另一个变量以免丢失原始输入。

    【讨论】:

    • 这个解决方案也很有效,谢谢:) -Daniel
    【解决方案4】:

    这是你需要的吗?

    List < string > _unWantedWords = new List < string > {
      "word1",
      "word2",
      "word3"
    };
    string input = "word1mdjw ksjcword2 d word3fjwu";
    
    for (int i = 0; i < _unWantedWords.Count; i++) {
      input = input.Replace(_unWantedWords[i], "");
    }
    

    DotNet 小提琴:https://dotnetfiddle.net/zoY4t7

    或者你可以简单地使用ForEachread more over here

     _unWantedWords.ForEach(x => {
        input = input.Replace(x, "");
    });
    

    【讨论】:

      猜你喜欢
      • 2012-08-18
      • 2021-10-08
      • 1970-01-01
      • 2017-12-06
      • 2013-12-03
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 2021-12-16
      相关资源
      最近更新 更多