Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I think I'm missing something here -- string.replace()

I have the code

String txt = "<p style=\"margin-top: 0\">";
txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");

In a for loop (which is what the i is for), but when I run this, nothing gets replaced. Am I using this wrong?

like image 461
Samsquanch Avatar asked Dec 21 '22 20:12

Samsquanch


2 Answers

The replace method does not modify the string on which it is called but instead returns the reference to the modified string.

If you want txt to refer to the modified string you can do:

txt = txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");

If you want txt to continue to refer to the original string and want a different reference to refer to the changed string you can do:

String new_txt = txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");
like image 37
codaddict Avatar answered Dec 24 '22 10:12

codaddict


It should look like this:

String txt = "<p style=\"margin-top: 0\">";
txt = txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");

"String" is an immutable type, which means that methods on a String do not change the String itself. More info here - http://en.wikipedia.org/wiki/Immutable_object.

like image 97
Greg Sansom Avatar answered Dec 24 '22 09:12

Greg Sansom