The fact that the replace method returns a string object rather than replacing the contents of a given string is a little obtuse (but understandable when you know that strings are immutable in Java). I am taking a major performance hit by using a deeply nested replace in some code. Is there something I can replace it with that would make it faster?
To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.
As you know, in Java, Strings are immutable. So every time we construct or concatenate a String object, Java creates a new String – this might be especially costly if done in a loop.
The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string. Syntax: The syntax of the replaceAll() method is as follows: public String replaceAll(String str, String replacement)
To replace the first occurrence of a character in Java, use the replaceFirst() method.
This is what StringBuilder is meant for. If you're going to be doing a lot of manipulation, do it on a StringBuilder
, then turn that into a String
whenever you need to.
StringBuilder
is described thus:
"A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization".
It has replace
(and append
, insert
, delete
, et al) and you can use toString
to morph it into a real String
.
The previous posts are right, StringBuilder/StringBuffer are a solution.
But, you also have to question if it is a good idea to do the replace on big Strings in memory.
I often have String manipulations that are implemented as a stream, so instead of replacing it in the string and then sending it to an OutputStream, I do the replace at the moment that I send the String to the outputstream. That works much faster than any replace.
This works much faster if you want this replace to implement a template mechanism. Streaming is always faster since you consume less memory and if the clients is slow, you only need to generate at a slow pace - so it scales much better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With