Reputation: 14426
I see String usage in the existing code with several concatenation. Sonar code coverage recommends using StringBuilder. I am updating the code to use StringBuilder. But I am wondering how to efficiently overwrite the existing content with a new string.
In the string representation, its like below:
String query = "select...";
if ( x ) {
query = "select xyz...";
}
With StringBuilder, I used this:
StringBuilder query = new StringBuilder("select...");
if ( x ) {
// I need to overwrite the existing stringbuilder content here
query = new StringBuilder("Select xyz..");
//or
query = query.replace(,,,);
//or
//Anything better
}
I was hoping there would be a method like:
query.replace("new string");
which overwrites entire existing string with the new string. But it is not available.
Upvotes: 3
Views: 12088
Reputation: 2289
For your usecase the following seems perfect:
private static final String SELECT_PRE = "Select";
private static final String SELECT_POST = "...";
StringBuilder query = new StringBuilder(SELECT_PREFIX+SELECT_POST);
if ( x ) {
query = query.insert(SELECT_PREFIX.length(), " xyz");
}
Upvotes: 0
Reputation: 525
Here is one solution, not the most elegant one, using StringBuilder.replace(int start, int end, String str)
Let's say there are two conditions:
Try the following
StringBuilder query = new StringBuilder("select...");
String x = "ele";
String term1 = "ele";
String newTerm1 = "xxx";
String term2 = "...";
String newTerm2 = "yyy";
if ( x.equals(term1) ) {
int start = query.indexOf(term1);
int end = start + term1.length();
query.replace(start, end, newTerm1);
}
else if (x.equals(term2)){
int start = query.indexOf(term2);
int end = start + term2.length();
query.replace(start, end, newTerm2);
}
System.out.println(query.toString());
Upvotes: 0