0
    String weatherLocation = weatherLoc[1].toString();
weatherLocation.replaceAll("how","");
weatherLocation.replaceAll("weather", "");
weatherLocation.replaceAll("like", "");
weatherLocation.replaceAll("in", "");
weatherLocation.replaceAll("at", "");
weatherLocation.replaceAll("around", "");
test.setText(weatherLocation);

weatherLocation still contains "like in"

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
joe dacoolguy
  • 309
  • 2
  • 8
  • 18

4 Answers4

12

Strings are immutable. String#replaceAll() method will create a new string. You need to re-assign the result back to the variable:

weatherLocation = weatherLocation.replaceAll("how","");

Now, since the replaceAll method returns the modified string, you can also chain multiple replaceAll call in single line. In fact, you don't need a replaceAll() here. It is required, when you want to replace substring matching a regex pattern. Simply use String#replace() method:

weatherLocation = weatherLocation.replace("how","")
                                 .replace("weather", "")
                                 .replace("like", "");
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
6

As Rohit Jain said, Strings are immutable; in your case you could chain calls to replaceAll to avoid multiple affectations.

String weatherLocation = weatherLoc[1].toString()
        .replaceAll("how","")
        .replaceAll("weather", "")
        .replaceAll("like", "")
        .replaceAll("in", "")
        .replaceAll("at", "")
        .replaceAll("around", "");
test.setText(weatherLocation);
Ahmed KRAIEM
  • 10,267
  • 4
  • 30
  • 33
2

Exactly as Rohit Jain said, and also, since replaceAll takes regex, instead of chaining calls you can simply do something like

test.setText(weatherLocation.replaceAll("how|weather|like|in|at|around", ""));
Sethiel
  • 182
  • 6
  • 14
1

I think that better will be to use StringBuilder/StringBuffer if you need to replace a lot of strings in text. Why? As Rohit Jain wrote String is immutable so every call of replaceAll method needs to create new object. Unlike String, StringBuffer/StringBuilder are mutable so it won't create new object (it will work on the same object).

You can read about StringBuilder for example in this Oracle tutorial http://docs.oracle.com/javase/tutorial/java/data/buffers.html.

pepuch
  • 6,346
  • 7
  • 51
  • 84