Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #296 Replace last occurrence of substring

Assign to x2 the value of string x with the last occurrence of y replaced by z.
If y is not contained in x, then x2 has the same value as x.

StringBuilder x2 = new StringBuilder(x);
int i = x2.lastIndexOf(y);
x2.replace(i, i + y.length(), z);
String x2 = x;
int i = x.lastIndexOf(y);
if (i != -1) {
    String t = x2.substring(0, i);
    x2 = t + z + x2.substring(i + y.length());
}
import static java.util.regex.Pattern.quote;
String p = quote(y), x2;
x2 = x.replaceAll(p + "(?!.*" + p + ')', z);
var position = x.lastIndexOf(y).clamp(0, x.length);
var x2 = x.replaceFirst(y, z, position);

New implementation...
< >
programming-idioms.org