Reputation:
I want to swap character groups in a String. For example:
swap("aabbcdefg","aa","bb") = bbaacdefg
swap("aabbcdefg","aa","efg") = efgbbcdaa
I did something like this:
static String swap(String val, String sub1, String sub2)
{
String temp="tt";
val= val.replace(sub1,temp);
val= val.replace(sub2,sub1);
val= val.replace(temp,sub2);
return val;
}
Can I do it in more efficient way?
Upvotes: 1
Views: 76
Reputation: 9172
The original code would break if trying to handle tt
.
This code splits by sub1
, loops through and replaces sub2
with sub1
and joins with sub2
.
static String swap(String val, String sub1, String sub2)
{
String[] items = val.split(sub1);
for (int i=0; i<items.length; i++)
{
items[i] = items[i].replace(sub2, sub1);
}
return String.join(sub2, items);
}
Upvotes: 2