How to replace the last occurrence of a substring in a string with Pascal

1 Answer

0 votes
program ReplaceLastOccurrence;

function RPos(const SubStr, S: string): Integer;
var
  I: Integer;
begin
  RPos := 0;
  for I := Length(S) - Length(SubStr) + 1 downto 1 do
    if Copy(S, I, Length(SubStr)) = SubStr then
    begin
      RPos := I;
      Break;
    end;
end;

function ReplaceLast(const Input, OldSub, NewSub: string): string;
var
  LastPos: Integer;
begin
  LastPos := RPos(OldSub, Input); // Find the last occurrence of OldSub
  if LastPos > 0 then
    ReplaceLast := Copy(Input, 1, LastPos - 1) + NewSub +
                   Copy(Input, LastPos + Length(OldSub), Length(Input))
  else
    ReplaceLast := Input; // If OldSub is not found, return the original string
end;


var
  Str: string;
begin
  Str := 'This is a test. This is a test. This is a test.';
  
  Str := ReplaceLast(Str, 'test', 'not');

  WriteLn('Result: ', Str);
end.




(*
run:

Result: This is a test. This is a test. This is a not.

*)

 



answered Aug 16, 2025 by avibootz
...