2017年6月20日 星期二

Delphi POS 增強功能 : 最後位置,第 N 次位置,出現次數

http://delphi.ktop.com.tw/board.php/00_01_21/post.php?action=usereply&cid=31&fid=79&tid=28123&rid=183889&iid=2207


這只是很簡單的增強 POS 功能的 function ,不知有沒人 POST 過類似的    PosEnd 是回傳 SubStr 在 S 最後一次出現的位置,若沒出現回傳 0    PosN 是回傳 SubStr 在 S 第 n 次出現的位置,若出現少於n次回傳 0    PosCount 是回傳 SubStr 在 S 出現的次數    放這些 Function 的 Unit 要加 use StrUtils
function PosEnd(Substr,S: string): Integer;
var
  i : integer;
begin
  i := 0;
  repeat
    result := i;
    i := i   1;
    i := PosEx(SubStr,S,i)
  until i <= 0
end;    function PosN(Substr,S: string; N : Integer): Integer;
var
  i: integer;
begin
  result := 0;
  For i := 1 to N do
  begin
    result := result   1;
    result := PosEx(SubStr,S,result);
  end;
end;    function PosCount(SubStr,S : string) : Integer;
var
  i : integer;
begin
  i := 0;
  result := -1;
  repeat
    result := result   1;
    i := i   1;
    i := PosEx(SubStr,S,i)
  until i <= 0
end;
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;

沒有留言:

張貼留言