0

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

1
  • If the list is long enough, consider using StringBuilder.Replace instead of String.Replace. It doesn't through off garbage like string manipulation does Commented Oct 19, 2021 at 17:01

4 Answers 4

1

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. assign to input)

Sign up to request clarification or add additional context in comments.

1 Comment

"input = _unWantedWords.Aggregate(input, (s, w) => s.Replace(w, ""));" did it for my case, as the words just needed to be removed in the order of which they appeared. Thanks for the response :) Daniel
0

You can use ForEach instead

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

Comments

0

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.

1 Comment

This solution worked as well, thanks :) -Daniel
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.