String.replace不工作

时间:2014-12-09 18:06:45

标签: java string

我试图将此String中的“X”替换为另一个char,方法是将其发送给方法...

这是我发送的字符串:

adress = "http://developer.android.com/sdk/api_diff/X/changes.html";
//Caliing method
getadress(adress,i)

这是方法:

private static String getadress(String stadress, Integer i) {
    stadress.replaceAll("X",i.toString());
    System.out.print(stadress);
    return stadress;
}

该方法对我不起作用,我想这是因为我没有正确使用它。

我想做的事情:

adress.replace("X","2"); //for example ...

2 个答案:

答案 0 :(得分:2)

String进行操作的方法返回更改后的结果;他们不会修改原始String。变化

stadress.replaceAll("X",i.toString());

stadress = stadress.replaceAll("X",i.toString());

答案 1 :(得分:1)

你几乎把它弄好了。您只需要使用新值更新stadress变量:

private static String getadress(String stadress, Integer i) {
   stadress = stadress.replaceAll("X",i.toString());//assign with new value here
   System.out.print(stadress);
   return stadress;
}

或者,作为实现这一目标的更短途径:

private static String getadress(String stadress, Integer i) {
   return stadress.replaceAll("X",i.toString());//assign with new value here on one line
   //System.out.print(stadress);
   //return stadress;
}
相关问题