java.lang.String.replace 问题的提示?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1166905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hints for java.lang.String.replace problem?
提问by CL23
I would like to replace "." by "," in a String/double that I want to write to a file.
我想替换“。” 通过“,”在我想写入文件的字符串/双精度值中。
Using the following Java code
使用以下 Java 代码
double myDouble = myObject.getDoubleMethod(); // returns 38.1882352941176
System.out.println(myDouble);
String myDoubleString = "" + myDouble;
System.out.println(myDoubleString);
myDoubleString.replace(".", ",");
System.out.println(myDoubleString);
myDoubleString.replace('.', ',');
System.out.println(myDoubleString);
I get the following output
我得到以下输出
38.1882352941176
38.1882352941176
38.1882352941176
38.1882352941176
Why isn't replace doing what it is supposed to do? I expect the last two lines to contain a ",".
为什么不替换做它应该做的事情?我希望最后两行包含一个“,”。
Do I have to do/use something else? Suggestions?
我必须做/使用其他东西吗?建议?
回答by AlbertoPL
You need to assign the new value back to the variable.
您需要将新值分配回变量。
double myDouble = myObject.getDoubleMethod(); // returns 38.1882352941176
System.out.println(myDouble);
String myDoubleString = "" + myDouble;
System.out.println(myDoubleString);
myDoubleString = myDoubleString.replace(".", ",");
System.out.println(myDoubleString);
myDoubleString = myDoubleString.replace('.', ',');
System.out.println(myDoubleString);
回答by Chris Kessel
The original String isn't being modified. The call returns the modified string, so you'd need to do this:
原始字符串没有被修改。该调用返回修改后的字符串,因此您需要执行以下操作:
String modded = myDoubleString.replace(".",",");
System.out.println( modded );
回答by vh.
The bigger question is why not use DecimalFormatinstead of doing String replace?
更大的问题是为什么不使用DecimalFormat而不是进行字符串替换?
回答by dfa
replacereturns a new String(since String is immutable in Java):
replace返回一个新字符串(因为 String 在 Java 中是不可变的):
String newString = myDoubleString.replace(".", ",");
回答by Brian Beckett
Always remember, Strings are immutable. They can't change. If you're calling a String method that changes it in some way, you need to store the return value. Always.
永远记住,字符串是不可变的。他们不能改变。如果您正在调用以某种方式更改它的 String 方法,则需要存储返回值。总是。
I remember getting caught out with this more than a few times at Uni :)
我记得在 Uni 时不止一次被这个问题所困扰:)

