简体   繁体   中英

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. 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?

 "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 ):

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

we can't change string itself, but we can change reference (ie assing to 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

Or you can simply use ForEach , read more over here

 _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.

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

You can create another variable as to not lose the original input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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