1

I would like to ask you how I could implement a function that for each string in a list execute something. This should be the case:

list={"a", "upon", "time", "once", ...}

What I am trying to do is removing from a text, example= {"once upon a time"}, those strings but one by one. This means that I should be able to check if a is in the text. If it is, then I should remove it. And so on. I would do that using a for loop in C. I am new in using Mathematica, so I hope you can help me. Would it possible to print the results one by one (for example: example={"once upon time"}, {"once a time"}, {"once upon a"}...)?

Thank you for your time.

Val
  • 225
  • 1
  • 6

1 Answers1

1
list = {"a", "upon", "time", "once"}
example = {"once upon a time"}

Map[StringReplace[example, # :> ""] &]@list

{{"once upon time"}, {"once a time"}, {"once upon a "}, {" upon a time" }}

Aside: if you want apply the replacement recursively:

FoldList[StringReplace[#, #2 :> ""] &, example, list]

{{"once upon a time"}, {"once upon time"}, {"once time"}, {"once " }, {" "}}

kglr
  • 394,356
  • 18
  • 477
  • 896
  • thank you kglr. Yes, this is what I was looking for. I tried with Map and StringReplace, but I forgot to add the list at the end. I am really new in using Mathematica. If I wanted to do the opposite, i.e. to keep the elements of the list instead of removing them (example: "once" -> "once"} but keeping their positions, how could I do? – Val Sep 20 '19 at 23:10
  • @Val, thank you for the accept. And welcome to mma.se. What would be desired result for "opposite" case in the context of example and list? – kglr Sep 20 '19 at 23:14
  • Thanks kglr. I would like to keep the word in the example, but removing all the other words and keeping their positions (replacing the words removed with blank spaces, for example) – Val Sep 20 '19 at 23:20
  • @Val, maybe something like Map[StringReplace[example, Alternatives @@ Complement[list, {#}] :> ""] &, list]? – kglr Sep 20 '19 at 23:33
  • Unfortunately, it cannot do what I am looking for. It should take/keep only the elements in the list, removing all the other characters from example. I was thinking of except, but it does the opposite (I think). Thank you for your help and for your time, kglr – Val Sep 22 '19 at 16:28