Logo

Programming-Idioms

  • Haskell
  • C++
  • Dart

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.

var position = x.lastIndexOf(y).clamp(0, x.length);
var x2 = x.replaceFirst(y, z, position);
  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.

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