Replace final occurance of a substring

Please discuss general Delphi programming topics here.

Replace final occurance of a substring

Postby mathgod » October 15th, 2009, 8:52 pm

I am drawing a blank on this one and I think the solution will be simple. I know how to replace the first occurrence of a substring by using the pos function but how do I replace the final occurrence of a substring? There must be a more efficient way to do this than reversing the string values.
User avatar
mathgod
Junior Member
Junior Member
 
Posts: 35
Joined: December 15th, 2007, 4:36 pm
Location: Middle of New Mexico, USA

Re: Replace final occurance of a substring

Postby Kambiz » October 16th, 2009, 9:17 am

The following function works like Pos function except that it begins the search from end of string.

Code: Select all
function RPos(const SubStr, Str: String): Integer;
var
  I, X: Integer;
  LenSubStr: Integer;
begin
  I := Length(Str);
  LenSubStr := Length(SubStr);
  while I >= LenSubStr do
  begin
    if Str[I] = SubStr[LenSubStr] then
    begin
      X := 1;
      while (X < LenSubStr) and (Str[I - X] = SubStr[LenSubStr - X]) do
        Inc(X);
      if X = LenSubStr then
      begin
        Result := I - LenSubStr + 1;
        Exit;
      end;
    end;
    Dec(I);
  end;
  Result := 0;
end;
Kambiz
User avatar
Kambiz
Administrator
Administrator
 
Posts: 2430
Joined: March 7th, 2003, 7:10 pm

Re: Replace final occurance of a substring

Postby mathgod » October 17th, 2009, 4:31 am

Thank you, Kambiz.
User avatar
mathgod
Junior Member
Junior Member
 
Posts: 35
Joined: December 15th, 2007, 4:36 pm
Location: Middle of New Mexico, USA


Return to Delphi Programming

Who is online

Users browsing this forum: No registered users and 4 guests

cron