Logo

Programming-Idioms

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

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.

StrUtils
  x2 := ReverseString(StringReplace(ReverseString(x), ReverseString(y), ReverseString(z), []));

Just for the fun of doing it in a one-liner...
StrUtils
  x2 := x;
  p := RPos(y, x);
  if (p > 0) then
  begin
    Delete(x2, p, Length(y));
    Insert(z, x2, p);
  end;
var position = x.lastIndexOf(y).clamp(0, x.length);
var x2 = x.replaceFirst(y, z, position);

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