Replace final occurance of a substring

Posted:
October 15th, 2009, 8:52 pm
by mathgod
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.
Re: Replace final occurance of a substring

Posted:
October 16th, 2009, 9:17 am
by Kambiz
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;