This site requires JavaScript, please enable it in your browser!
Greenfoot back
Gevater_Tod4711
Gevater_Tod4711 wrote ...

2012/10/20

need help with String.replace()

Gevater_Tod4711 Gevater_Tod4711

2012/10/20

#
Hi all, I want to change a part of a string using replace but it doesn't work and I don't get why. An simple example is this:
String s = "any string";
s.replace("any string", "another string");//should change the string but it doesn't;
System.out.println(s);//the string is still "any string" and not "another string";
Doe's anyone know what I am doing wrong?
SPower SPower

2012/10/20

#
The replace method returns a new String object, it doesn't change the String you call it on: a String is immutable. Do this:
s = s.replace(...);
SPower SPower

2012/10/20

#
And btw, the replace method takes 2 chars, shouldn't you use the replaceAll or the replaceFirst method?
Gevater_Tod4711 Gevater_Tod4711

2012/10/20

#
Oh right I should have seen that. I realy should read the API's better. Thank you SPower. And there is a nother replace method. Your links refer to an old API in the new there is also this replace method which has CharSequence's as the parameters. But using replaceAll would be better i think.
SPower SPower

2012/10/20

#
O, I always click on the old API :(, I'll keep that in mind next time ;)
You need to login to post a reply.