6

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(" ", "+");
2
  • I assume it is just for this example, but I just want to point out that I wouldn't name a variable "string".... Commented Jan 19, 2011 at 0:29
  • 1
    if you are doing this for url encoding purposes, take a look at the URLEncoder class Commented Jan 19, 2011 at 0:58

2 Answers 2

26

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(" ", "+");
Sign up to request clarification or add additional context in comments.

2 Comments

+1 Exactly. String.replace returns a string. It is an accessor, not a direct mutator.
@jor - if this is the correct answer, check the box next to it so @Cristian gets credit.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.