1

How can I replace it? I've been trying this:

string.replaceFirst(substring, "");

but it's not replacing, and as I am doing a recursive method, it's giving me a StackOverflowException..

Any idea?

4 Answers 4

8

String are immutable, which means you cannot change them once they are initialized.

The replaceFirst method creates a new string where the first instance is replaced by your replacement and returns it...the original string is never modified.

You're code should be something like this

string = string.replaceFirst(substring,"")
Sign up to request clarification or add additional context in comments.

5 Comments

@st0le: an answer can at earliest only be accepted 15 minutes after the question is been posted.
@BalusC, hehe, but its no parrot... :P
If you didn't notice, yesterday toinght I've updated my Gravatar as well.
@BalusC, I did , but between the both of us you're 1 cap and a Chichiray ahead of me.... :P
@BalusC-Would you mind taking a look at this ?: stackoverflow.com/questions/4532009/…
3

In addition to other replys that Strings are immutable, note that replaceFirst takes in a Regular Expression not a substring. (The two might be the same in some cases but not all). Either way this more than likely is unrelated to your StackOverflowException.

Comments

2

This method not modifying current String. It returns new string with replacement. String newString = string.replaceFirst(substring, "");

Comments

0

Use this:

string = string.replaceAll(substring, replacement_string).

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.