增量字符串退避

时间:2013-12-19 16:00:41

标签: delphi firemonkey delphi-xe5

使用Delphi XE-5 Firemonkey mobile

我有一个类似于

的字符串(Path)
host domain and node here\\something1\\something2\\something3\\something4\\something5

我需要一个能够在每次调用时删除每个部分的函数。例如,当第一次调用该函数时,它将删除“\ something5”将字符串保留为

something1\\something2\\something3\\something4

function CountOccurences( const SubText: string;
                          const Text: string): Integer;
begin
  if (SubText = '') OR (Text = '') OR (Pos(SubText, Text) = 0) then
    Result := 0
  else
    Result := (Length(Text) - Length(StringReplace(Text, SubText, '', [rfReplaceAll]))) div  Length(subtext);
end; {Robert Frank}

 function IncrementalBackOff(aPath: String): String;
 var
  I: Integer;
  Found: Boolean;
 begin
  result:= aPath;
  if (CountOccurences('\\', result) > 1) then
  begin
   for I:= Length(result) downto 1 do
   begin
    if (result[I] <> '\') then
     Delete(result, I, 1)
    else
    begin
     Delete(result, I, 1);
     Delete(result, I-1, 1);
    end;
   end;
  end;
 end;

注意:我需要始终保留第一部分(即永远不要删除'\\ something1'

host domain and node here\\something1

因此,该函数必须每次返回keepng字符串

2 个答案:

答案 0 :(得分:3)

这不是最短的版本,但它仍然很短且可读:

function ReducePath(const Path: string): string;
var
  i: Integer;
begin
  result := Path;
  if PosEx('\\', Path, Pos('\\', Path) + 2) = 0 then Exit;
  for i := Length(result) - 1 downto 1 do
    if Copy(result, i, 2) = '\\' then
    begin
      Delete(result, i, Length(result));
      break;
    end;
end;

代码较短但效率低下:

function ReducePath(const Path: string): string;
begin
  result := Path;
  if PosEx('\\', Path, Pos('\\', Path) + 2) = 0 then Exit;
  Result := Copy(Result, 1, Length(Result) - Pos('\\', ReverseString(Result)) - 1);
end;

答案 1 :(得分:1)

RTL具有ExtractFileDir()功能,用于此目的。还有ExtractFilePath(),虽然它保留了尾随分隔符,而ExtractFileDir()将其删除。