-1

Using 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. e.g., when call the function the first time, it would remove "\something5" leaving the string as

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 (i.e. never delete '\\something1'

host domain and node here\\something1

So, the function must return the remainng string each time

JakeSays
  • 2,048
  • 8
  • 29
  • 43

2 Answers2

3

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;
Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
1

The RTL has an ExtractFileDir() function for this exact purpose. There is also ExtractFilePath(), though it leaves the trailing delimiter intact, whereas ExtractFileDir() removes it.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • It does not help here, but `ExtractFileDir` would do. A `Path` always include a trailing path delimiter. If not it is a directory or a file – Sir Rufo Dec 19 '13 at 17:56
  • Both of these functions only remove a single backslash. @Remy, are you reading this as C++ with escaped backslashes? – David Heffernan Dec 19 '13 at 19:44