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?
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.
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 + "\"");
String is a immutable class, which means instance methods of a String object don't alter the string itself. You have to gather the return value of those instance methods.
精彩评论