Delphi StrUtils.PosEx

Delphi StrUtils.PosEx -  返回子字符串的索引值,从指定位置开始。

源码(PosEx):

function PosEx(const SubStr, S: string; Offset: Cardinal = 1): Integer;
var
  I,X: Integer;
  Len, LenSubStr: Integer;
begin
  if Offset = 1 then
    Result := Pos(SubStr, S)
  else
  begin
    I := Offset;
    LenSubStr := Length(SubStr);
    Len := Length(S) - LenSubStr + 1;
    while I <= Len do
    begin
      if S[I] = SubStr[1] then
      begin
        X := 1;
        while (X < LenSubStr) and (S[I + X] = SubStr[X + 1]) do
          Inc(X);
        if (X = LenSubStr) then
        begin
          Result := I;
          exit;
        end;
      end;
      Inc(I);
    end;
    Result := 0;
  end;
end;

说明:

  • PosEx返回S中SubStr的索引,开始在偏移处搜索。如果偏移量为1(默认),PosEx 相当于 Pos 函数。
  • 如果找不到子字符串、偏移大于S长度或偏移小于1,则PosEx返回0。

  

示例:

//从第几个字符开始,搜索字串的位置 PosEx
var
  ss,s: string;
  i: Integer;
begin
  ss := 'Hello Delphi7';
  s := 'llo';
  i := PosEx(s,ss,2);
  ShowMessage(IntToStr(i));  //3
end;

延伸:查看Pos函数 

创建时间:2021.05.06  更新时间: 

博客园 滔Roy https://www.cnblogs.com/guorongtao 希望内容对你所有帮助,谢谢!
原文地址:https://www.cnblogs.com/guorongtao/p/14735574.html