Be concise.
Be useful.
All contributions dictatorially edited by webmasters to match personal tastes.
Please do not paste any copyright violating material.
Please try to avoid dependencies to third-party libraries and frameworks.
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
x and x2 are allocatable characters.
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());
}
StringBuilder x2 = new StringBuilder(x);
int i = x2.lastIndexOf(y);
x2.replace(i, i + y.length(), z);
String p = quote(y), x2;
x2 = x.replaceAll(p + "(?!.*" + p + ')', 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;
perl substr can be used as an lvalue, which is ideal here. We use rindex to find the last occurence of substring $y in $x and use that position in a substr of a copy of $x called $x2. Assigning $z to the substring replaces it -- but we skip that if rindex didn't find the substring.
x2 = z.join(x.rsplit(y, 1))
x2 = x.gsub(/#{y}(?!.*#{y})/, z )
Regex with negative lookahead.