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?
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 + "\"");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With