I am trying to replace the "X" in this String with another char by sending it to a method...
This is the String I'm sending:
adress = "http://developer.android.com/sdk/api_diff/X/changes.html";
//Caliing method
getadress(adress,i)
and this is the method:
private static String getadress(String stadress, Integer i) {
stadress.replaceAll("X",i.toString());
System.out.print(stadress);
return stadress;
}
The method doesn't work for me and I guess it's because I'm not using it correctly.
What I was trying to do:
adress.replace("X","2"); //for example ...
Heretic Monkey
12.2k7 gold badges63 silver badges133 bronze badges
asked Dec 9, 2014 at 18:06
TubusMan
1791 gold badge1 silver badge11 bronze badges
2 Answers 2
Methods that operate on Strings return the changed result; they do not modify the original String. Change
stadress.replaceAll("X",i.toString());
to
stadress = stadress.replaceAll("X",i.toString());
answered Dec 9, 2014 at 18:09
rgettman
179k30 gold badges282 silver badges365 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You almost had it right. You just need to update the stadress variable with the new value:
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;
}
Or, as a shorter way of achieving this:
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;
}
answered Dec 9, 2014 at 18:12
Drew Kennedy
4,1564 gold badges28 silver badges35 bronze badges
Comments
lang-java