我正在尝试用另一个字符替换字符串的一个字符,但无法做到这一点。我为此使用了字符串函数法典。
String text;
text="2:15";
if(text.contains(":"))
{
replace(":",".");
}
Log.i("Tag",text);
我想将 2:15 更改为 2.15,但它保持不变。
String text;
text= "2:15";
if(text.contains(":"))
{
replace(":","."); // Will not cause anything as String is immutable.
}
Log.i("Tag",text);
更改为
String text;
text="2:15";
if(text.contains(":")){
text = text.replace(":",".");
}
Log.i("Tag",text);
阅读字符串及其不可变属性。
字符串在 Java 中是不可变的 - replace 不会更改现有字符串,它会返回一个新字符串。你想要:
String text="2:15";
if(text.contain(":"))
{
text = text.replace(":",".");
}
Log.i("Tag",text);
使用这段代码
String text = "2:15";
text = text.replace(":",".");
-
text.replace(":",".");
返回一个新字符串,因此您必须将其分配给某个变量。 在这种情况下text
。 - 我还删除了
text.contains(":")
因为它是一个不必要的调用,如果它不包含要替换的字符串,替换最终将不替换任何内容。