Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings in android/java, replace() does nothing

In android/java, I'm trying to replace the space in some strings with a +, but it doesn't seem to work. Am I doing it wrong?

String string="Hello world";
string.replace(" ", "+");
like image 953
jor Avatar asked Jan 19 '11 00:01

jor


2 Answers

String objects are immutable, so the replace method doesn't change the string but creates a new one that you have to re-save:

String string="Hello world";
string = string.replace(" ", "+");
like image 99
Cristian Avatar answered Oct 10 '22 19:10

Cristian


In Java, the StringBuffer class provides a mutable string. The replace method will return the same object.

like image 31
rvasa Avatar answered Oct 10 '22 19:10

rvasa