我正在尝试将最终的String变量的值更改为" #mango"没有重新赋值,最好是使用StringBuffer和StringBuilder:
public static void main(String[] args) {
String finaal = "i am #apple";
//Case 1: Apache Commons Lang 3
StringUtils.replace(finaal, "#apple", "#mango");
System.out.println(finaal);//--expected "i am #mango" but actual "i am #apple"
//Case 2 :
finaal.replace("#apple", "#mango");
System.out.println(finaal);//--expected "i am #mango" actual "i am #mango" but need re-assignment here
}
答案 0 :(得分:1)
字符串是不可变的,替换的结果是从replace方法返回的。如果你想在没有重新分配的情况下进行替换,你需要将你的字符串包装在另一个类中。
public static void main (String[] args) {
StringHolder stringHolder = new StringHolder("#apple");
stringHolder.replace("#apple", "#mango");
System.out.println(stringHolder);
}
private static class StringHolder {
private String str;
public StringHolder(String str) {
this.str = str;
}
public void replace(String from, String to) {
String newStr = str.replace(from, to);
this.str = newStr;
}
public String toString() {
return str;
}
}