public static String reverse(String x) {
Matcher m = Pattern.compile("\\w+").matcher(x);
if(!m.find()) return x;
StringBuffer target = new StringBuffer(x.length());
do m.appendReplacement(target, new StringBuilder(m.group()).reverse().toString());
while(m.find());
return m.appendTail(target).toString();
}
appendReplacement loop + appendTail a Matcher String.replaceAll(regex), , , , , .
Unfortunately, we must use the deprecated one StringBufferhere since the API is older StringBuilder. Java 9 is going to change that .
A potentially more effective alternative is
public static String reverse(String x) {
Matcher m = Pattern.compile("\\w+").matcher(x);
if(!m.find()) return x;
StringBuilder target = new StringBuilder(x.length());
int last=0;
do {
int s = m.start(), e = m.end();
target.append(x, last, s).append(new StringBuilder(e-s).append(x, s, e).reverse());
last = e;
}
while(m.find());
return target.append(x, last, x.length()).toString();
}
This uses StringBuilderthroughout the operation and uses the function of adding partial sequences of characters without creating intermediate lines for matching and replacing. It also speeds up the search for placeholders in replacements that appendReplacementit does internally.
source
share