Matthew Hipkin

PHP style explode function for Delphi

Download: http://www.matthewhipkin.co.uk/programs/explodefunc.tar.gz

This is a very useful function to have, requires less effort than using a TStrings CommaText value.

(Originally found here.)

type
  TArray = array of string;

function explode(cDelimiter,  sValue : string; iCount : integer) : TArray;
var
  s : string; i,p : integer;
begin
  s := sValue; i := 0;
  while length(s) > 0 do
  begin
    inc(i);
    SetLength(result, i);
    p := pos(cDelimiter,s);
    if ( p > 0 ) and ( ( i < iCount ) OR ( iCount = 0) ) then
    begin
      result[i - 1] := copy(s,0,p-1);
      s := copy(s,p + length(cDelimiter),length(s));
    end else
    begin
      result[i - 1] := s;
      s :=  '';
    end;
  end;
end;

end.

Example usage:

var
  s: String;
  i: integer;
  a: TArray;
begin
  s := 'hello,there,how,are,you?';
  a := explode(',',s,0);
  for i := 0 to High(a) do writeln(a[i]);
end.
blog comments powered by Disqus
Flag Counter