(* Collection of code snippets by Arne Vajhøj *)
(* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) *)
program multireplace;

{$APPTYPE CONSOLE}

uses
  SysUtils, Windows;

function strip1(s : string) : string;

var
  tmp, oldtmp : string;

begin
  tmp := s;
  repeat
     oldtmp := tmp;
     tmp := StringReplace(tmp, '  ', ' ', [rfReplaceAll]);
  until tmp = oldtmp;
  result := tmp;
end;

function strip2(s : string) : string;

var
  tmp : string;

begin
  tmp := s;
  while pos('  ', tmp) > 0 do
    tmp := StringReplace(tmp, '  ', ' ', [rfReplaceAll]);
  result := tmp;
end;

function strip3(s : string) : string;

var
  tmp : string;
  p : integer;

begin
  tmp := s;
  repeat
    p := pos('  ', tmp);
    if p > 0 then
      Delete(tmp, p , 1);
  until p = 0;
  result := tmp;
end;

function strip4(s : string) : string;

var
  tmp : string;
  i : integer;

begin
  tmp := s;
  i := length(tmp);
  while i > 1 do begin
    if (tmp[i] = ' ') and (tmp[i-1] = ' ') then
      Delete(tmp, i, 1);
    dec(i);
  end;
  result := tmp;
end;

function strip5(s : string) : string;

var
  tmp : string;
  i, ix : integer;

begin
  tmp := s;
  ix := 1;
  for i := 1 to length(s) do begin
    if (s[i] <> ' ') or ((i > 1) and (s[i-1] <> ' ')) then begin
      tmp[ix] := s[i];
      inc(ix);
    end;
  end;
  result := copy(tmp, 1, ix);
end;

const
  N = 1000000;

var
  s : string;
  i, t1, t2 : integer;

begin
  s := '1 2  3   4    5     |';
  writeln(strip1(s));
  writeln(strip2(s));
  writeln(strip3(s));
  writeln(strip4(s));
  writeln(strip5(s));
  t1 := GetTickCount();
  for i := 1 to N do strip1(s);
  t2 := GetTickCount();
  writeln(t2-t1);
  t1 := GetTickCount();
  for i := 1 to N do strip2(s);
  t2 := GetTickCount();
  writeln(t2-t1);
  t1 := GetTickCount();
  for i := 1 to N do strip3(s);
  t2 := GetTickCount();
  writeln(t2-t1);
  t1 := GetTickCount();
  for i := 1 to N do strip4(s);
  t2 := GetTickCount();
  writeln(t2-t1);
  t1 := GetTickCount();
  for i := 1 to N do strip5(s);
  t2 := GetTickCount();
  writeln(t2-t1);
  readln;
end.
