0

Is it possible to replace() multiple strings at once?


For example:
String X = new String("I will find cookies");
String newX = X.replace(("will", "won't") + ("I", "You"));
System.out.print(newX);

OUTPUT

You won't find cookies

I know what I did was wrong and will create an error but at least you get my idea of "replacing multiples". If it's possible, what would be the better solution to this?

sreffejnnayr
  • 117
  • 1
  • 10
  • 3
    How about calling `replace` multiple times? – Luiggi Mendoza Dec 14 '15 at 15:42
  • My output string would change, wouldn't it? I have tried it, and the replaced strings would just `append` to my output or maybe I'm just doing it wrong. Can you call `replace` multiple times w/o changing the output? – sreffejnnayr Dec 14 '15 at 15:43
  • 2
    Your string won't change because it's immutable, but the result of that will have the replacements you're looking for. For example, you can do this: `newX = X.replace("will", "won't").replace("I", "You");` – Luiggi Mendoza Dec 14 '15 at 15:45
  • What does "*at once*" mean in your case? – PM 77-1 Dec 14 '15 at 15:47
  • Ohhh im newbie at java. Still on my freshman year tho. Anyway, if that's right and would fit my question, you should put your comment as an answer so people would see it! :) – sreffejnnayr Dec 14 '15 at 15:51
  • I think @LuiggiMendoza explained it very well already. Problem solved. Thanks a lot. – sreffejnnayr Dec 14 '15 at 15:54

2 Answers2

0

You can do a chained call of replace() like below:

String X = new String("I will find cookies");
String newX = X.replace("will", "won't").replace("I", "You");
System.out.print(newX);
Prerak Sola
  • 9,517
  • 7
  • 36
  • 67
0

The simplest answer (I can think of) here is:

String newX = X.replace("will", "won't").replace("I", "You");

This will be find for a simple example like this, but if you're trying to do anything bigger (i.e. many more replacements), you'd be wise to look into regular expressions instead.

DaveyDaveDave
  • 9,821
  • 11
  • 64
  • 77
  • Also, you haven't mentioned this in your question, but if you're hoping to replace multiple instances in the same string, for example, if your input were `I will find cookies, will you?`, and you wanted to replace both instances of `will`, you could use `X.replaceAll()`. – DaveyDaveDave Dec 14 '15 at 15:48