简体   繁体   English

用列表中的每个字符串替换一个字符串

[英]Replace a string with each string in a list

I have a list like so:我有一个这样的清单:

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

And I have a string like so:我有一个像这样的字符串:

string input = "word1mdjw ksjcword2 d word3fjwu";

I would like to remove the unwanted words in the input string, but strings are immutable in C#, so I though I would do something fancy in one swoop with a lambda expression.我想删除输入字符串中不需要的单词,但字符串在 C# 中是不可变的,所以我虽然我会用 lambda 表达式一次性做一些花哨的事情。 Like this:像这样:

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

But I can't seem to get it to work, any ideas?但我似乎无法让它工作,有什么想法吗? :) :)

Daniel丹尼尔

There're subtle problems in general case with the task:一般情况下,任务存在一些微妙的问题:

Shall we do it recursively ?我们应该递归地做吗?

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

What is the order of removing: if we want to remove {"ab", "bac"} what is the desired result for "XabacY" then?删除的顺序是什么:如果我们想删除{"ab", "bac"}那么"XabacY"的期望结果是什么?

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

In the simplest case (remove words in order they appear in _unWantedWords , no recursion ) you can put (let's use Linq since you've tried Select ):在最简单的情况下(删除单词以使其出现在_unWantedWords ,没有recursion )您可以放置​​(因为您已经尝试过Select所以让我们使用Linq ):

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

we can't change string itself, but we can change reference (ie assing to input )我们不能改变string本身,但我们可以改变引用(即分配到input

This is what you need?这是你需要的吗?

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 Fiddle : https://dotnetfiddle.net/zoY4t7点网小提琴: https : //dotnetfiddle.net/zoY4t7

Or you can simply use ForEach , read more over here或者你可以简单地使用ForEach在这里阅读更多

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

您可以使用ForEach代替

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

You can use the ForEach function to replace the text in the input.您可以使用 ForEach 函数来替换输入中的文本。

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

You can create another variable as to not lose the original input.您可以创建另一个变量,以免丢失原始输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM