Home > database >  Replace a string with each string in a list
Replace a string with each string in a list

Time:10-20

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

CodePudding user response:

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 (i.e. assing to input)

CodePudding user response:

You can use ForEach instead

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

CodePudding user response:

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.

CodePudding user response:

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, "");
});
  • Related