我试图将最终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
}
最佳答案
字符串是不可变的,替换的结果从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;
}
}