-3
public String plusOut(String str, String word){

String bob = str.replaceAll(^word,"+");

return bob;

}

Sample Input and Output:

I want to replace everything in String(str) that's not String(word) with a +

plusOut("1234xy5678", "xy")     == "++++xy++++"
plusOut("ghlnds4pl4qwqd4", "4") == "++++++4++4++++4"

^word<---how would I make the method replace everything except for word

I want to replace my String(str) with a "+" except the String(word). How would I go about doing this using replaceAll method.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Do you **have** to use `replaceAll`? Because if `word` is more than one character long, I don't think you can use it. Also, can `word` occur more than once in `str`? If so, do you want every occurrence of `word` to be preserved, or just the first (or last) one? – Ted Hopp Oct 18 '17 at 00:53
  • I would think that using replaceAll would be the easiest method for the problem since it is able to take a string and replace everything. The only thing is I want everything that is not the imputed String(word) – Kawaii Bird Oct 18 '17 at 01:00
  • Well you could also loop using indexOf – Scary Wombat Oct 18 '17 at 01:09
  • I could, but it would be easier just to do it in a couple of lines – Kawaii Bird Oct 18 '17 at 01:13
  • does this question help? https://stackoverflow.com/questions/977251/regular-expressions-and-negating-a-whole-character-group – Scary Wombat Oct 18 '17 at 01:57

1 Answers1

0

Your replaceAll method is almost there.

You need to change it to something like:

String bob = str.replaceAll("[^" + word + "]", "+");

You can see the two outputs requested here and here

achAmháin
  • 4,176
  • 4
  • 17
  • 40