简体   繁体   中英

What replace method can I use to replace a substring from a String?

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?

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,"")

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.

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

Use this:

string = string.replaceAll(substring, replacement_string).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM