您现在的位置:首页 >> 基础算法 >> window基础 >> 内容

12种方法返回2个文件路径之间的公共基路径ExtractBasePath

时间:2011/9/3 15:31:41 点击:

  核心提示:600) this.width = 600;'>方法一:Boris Kumparfunction ExtractBasePath(const Path1,Path2:string):string;co...

600) this.width = 600;">

方法一:Boris Kumpar

function ExtractBasePath(const Path1,Path2:string):string;
const
  PATH_DELIMITER = '\';
  DRIVE_DELIMITER = ':';
var
  P1,P2:PChar;
  cnt,j:Integer;
begin
  P1:=PChar(Path1) ;
  P2:=PChar(Path2) ;

  cnt := 1;
  j := 0;
  {$B-}
  while (P1^ <> #0) and (P2^ <> #0) and (UpCase(P1^) = UpCase(P2^) ) do
  begin
    if (P1^=PATH_DELIMITER) or (P2^=PATH_DELIMITER) or ((j=0) and (P1^=DRIVE_DELIMITER)) then j:=cnt;

    Inc(cnt) ;
    Inc(P1) ;
    Inc(P2) ;
  end;

  if (P1^=PATH_DELIMITER) or (P2^=PATH_DELIMITER) then j := cnt - 1;

  Result:=Copy(Path1,1,j) ;
end;

方法二:Pablo Anizio

function ExtractBasePath(const path1, path2 : string) : string;
var
  sP1, sP2, stemp, rslt: String;
  slP1, slP2: TStringList;
  dif: Boolean;
  cnt, max: integer;
begin
  rslt := EmptyStr;
  if ((path1 <> EmptyStr) and (path2 <> EmptyStr)) then
  begin
    sP1 := ExtractFilePath(path1) ;
    sP2 := ExtractFilePath(path2) ;

    slP1 := TStringList.Create;
    while length(sP1) <> 0 do
    begin
      stemp := Copy(sP1,1,pos('\',sP1)) ;
      Delete(sP1,1,pos('\',sP1)) ;
      slP1.Add(stemp) ;
    end;

    slP2 := TStringList.Create;
    while length(sP2) <> 0 do
    begin
      stemp := Copy(sP2,1,pos('\',sP2)) ;
      Delete(sP2,1,pos('\',sP2)) ;
      slP2.Add(stemp) ;
    end;

    dif := False;
    cnt := 0;
    if (slP1.Count >= slP2.Count) then
      max := slP2.Count
    else
      max := slP1.Count;

    while (not dif) and (cnt < max) do
    begin
      if slP1.Strings[cnt] = slP2.Strings[cnt] then
        rslt := rslt + slP1.Strings[cnt]
      else
        dif := True;
      inc(cnt) ;
    end;

    slP1.Free;
    slP2.Free;
  end;

  Result := rslt;
end;

方法三:Vlad Man

function ExtractBasePath(const path1, path2: string): string;
var
  j: Integer;
  vStrLength: Integer;
  vLastDelemiterIndex: Integer;
begin
  Result := '';

  if Length(path1) > Length(path2) then
    vStrLength := Length(path2)
  else
    vStrLength := Length(path1) ;

  for j := 1 to vStrLength do
    if path1[j] = path2[j] then
      Result := Result + path1[j]
    else
      Break;

  vLastDelemiterIndex := LastDelimiter('\', Result) ;
  Delete(Result, vLastDelemiterIndex + 1, Length(Result) - vLastDelemiterIndex) ;
end;

上一页1234下一页

作者:网络 来源:转载
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
  • 盒子文章(www.2ccc.com) © 2024 版权所有 All Rights Reserved.
  • 沪ICP备05001939号