# 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.

``````  character(len=:), allocatable :: x, x2, y, z

k = index(x,y,back=.true.)
if (k > 0) then
x2 = x(1:k-1) // z // x(k+len(y):)
else
x2 = x
end if
``````
``````var position = x.lastIndexOf(y).clamp(0, x.length);
var x2 = x.replaceFirst(y, z, position);``````
``import "strings"``
``````func replaceLast(x, y, z string) (x2 string) {
i := strings.LastIndex(x, y)
if i == -1 {
return x
}
return x[:i] + z + x[i+len(y):]
}``````
``StrUtils``
``````  x2 := x;
p := RPos(y, x);
if (p > 0) then
begin
Delete(x2, p, Length(y));
Insert(z, x2, p);
end;
``````
``StrUtils``
``````  x2 := ReverseString(StringReplace(ReverseString(x), ReverseString(y), ReverseString(z), []));
``````
``````\$x = 'A BB CCC this DDD EEEE this FFF';
\$y = 'this';
\$z = 'that';

\$x2 = \$x;
\$pos = rindex \$x, \$y;
substr(\$x2, \$pos, length(\$y)) = \$z
unless \$pos == -1;

print \$x2;
``````
``````x2 = z.join(x.rsplit(y, 1))
``````
``````x2 = x.gsub(/#{y}(?!.*#{y})/, z )
``````

programming-idioms.org