自写的LastPos,寻找字符串里的最后一个字符,RTL里没有提供这个函数——Delphi的String下标是从1开始的

时间:2022-01-04 09:02:21

已经好几次了,没有这个函数还是感觉很不方便,所以自己写了一个:

function LastPos(strFind :string; ch: Char): integer;
var
i, n: integer;
begin
Result := -;
if strFind='' then
begin
Exit;
end;
for i:=1 to Length(strFind) do
begin
if strFind[i]=ch then
Result := i;
end;
end; procedure TForm1.Button1Click(Sender: TObject);
var
s1: String;
begin
s1 := 'abc';
ShowMessage(s1[]);
ShowMessage(IntToStr(Length('/myaccount/save1/')));
ShowMessage(IntToStr(LastPos('/myaccount/save1/', '/')));
end;

当然,这里没有考虑效率和Unicode等问题,反正对D7比较好用。

另一个算法,看看别人怎么写的吧(倒序是非正常思路):

function LastPos(const S: string; C: Char): Integer;
var
i: Integer;
begin
i := Length(S);
while (i > ) and (S[i] <> C) do
Dec(i);
Result := i;
end;