HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Java string replace

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
replacestringjava

Problem

I am new to Java and I am trying to learn about optimizing code to make it production ready. I have the following code below. I would like to know how I could optimize it. I thought by using a small snippet of could, it would be a good way to learn.

Some points:

  • The function would be run many times to it needs to be fast.



  • The input is unconstrained since it might come from a user or from a file. Is there a way to deal with this so not exceptions are thrown? I was thinking of using a regular expression.



  • Is there anything else I need to do to make it production ready? e.g. unit tests. If so, what would be the best way to do this?



  • I am assuming that the string to be searched is not very long.



  • When I say optimization, I mean doing things like replacing the + operator with something faster is it can effect memory and performance, etc.



public String strReplave(String originalStr, String oldStr, String newStr) {
    int start = 0;
    while ((start = originalStr.indexOf(oldStr, start)) > 0) {
        originalStr= originalStr.substring(0,start) + newStr+ originalStr.substring(start + oldStr.length());
    start += newStr.length();
}
return originalStr;
}


Thanks for your help and if you need me to clarify anything please let me know.

Solution

String.replace(..) will work as Corbin said.

Be careful when you mix String objects with the '+' operator in Java, especially within a loop.

String s = a + b;


will be (generally) interpreted as

String s = new StringBuffer(a).append(b).toString();


While not bad on it's own, when performed in a loop, a new StringBuffer (or the newer StringBuilder) object will be created on every loop iteration, which is usually sub-optimal.

When you want to build a String up from pieces, consider storing the result in a StringBuilder object (created outside of the loop) as you go.

Code Snippets

String s = a + b;
String s = new StringBuffer(a).append(b).toString();

Context

StackExchange Code Review Q#17932, answer score: 5

Revisions (0)

No revisions yet.