简体   繁体   English

增量字符串退避

[英]incremental string backoff

Using Delphi XE-5 Firemonkey mobile 使用Delphi XE-5 Firemonkey mobile

I have a string (Path) that looks like this 我有一个看起来像这样的字符串(路径)

host domain and node here\\something1\\something2\\something3\\something4\\something5

I need a function that removes each portion with each call. 我需要一个函数来删除每个调用的每个部分。 eg, when call the function the first time, it would remove "\\something5" leaving the string as 例如,当第一次调用该函数时,它将删除“ \\ 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;

NOTE: I need to always keep the first section (ie never delete '\\\\something1' 注意:我需要始终保留第一部分(即,永远不要删除'\\\\ something1'

host domain and node here\\something1

So, the function must return the remainng string each time 因此,函数每次必须返回剩余的字符串

This is not the shortest version, but it is still quite short and rather readable: 这不是最短的版本,但仍然很短并且可读性强:

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;

Shorter code but inefficient: 代码较短,但效率低下:

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;

The RTL has an ExtractFileDir() function for this exact purpose. RTL具有用于此确切目的的ExtractFileDir()函数。 There is also ExtractFilePath() , though it leaves the trailing delimiter intact, whereas ExtractFileDir() removes it. 还有一个ExtractFilePath() ,尽管它使结尾的定界符保持不变,而ExtractFileDir()删除了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM