Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

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