问题
boolean b1 = false;
boolean b2 = true;
String s = new String(b1+""+b2);
s.replaceAll("false", "f");
s.replaceAll("true", "t");
Nothing is replaced. I still get "false true". I want to replace all "false" and "true", of the String, to "f" and "t".
Im pretty sure Im not doing it the right way, and thats why I need your help, which will be greatly appreciated.
回答1:
String in java is immutable, which means, once created, the value of a String object will not change.
The method replaceAll() (or almost all other methods in String class) hence are designed to return a new string rather than modifying the old one.
So the call should be made as
s = s.replaceAll("false", "f");
More on immutability is here
回答2:
Strings are immutable. When you do any operations on strings it creates new string. You need to assign results to a reference again
It should be something like s = s.replaceAll("false", "f");
回答3:
When you calls.replaceAll("false", "f"), you're not actually mutating the String at all. You need to assign that value to s like so:
s = s.replaceAll("false", "f");
回答4:
System.out.println(s.replaceAll("false", "f ").replaceAll("true", "t "));
回答5:
You need to write it like this:
s = s.replaceAll("false", "f");
s = s.replaceAll("true", "t");
Strings are immutable so once you declare them they cant be changed. Calling this s.replaceAll("false", "f");
creates a new string object with "f"
instead of "false"
. Since you weren't assigning this new object to a variable the new string was basically lost and your left with the original string.
回答6:
First of all, you need to realize that String
is immutable. This means that its contents cannot be changed. In order to get the result of the replaceAll() method, you need to assign the return value to a String
.
来源:https://stackoverflow.com/questions/11615305/cannot-to-replace-a-string-to-another-boolean-value-java