20 February 2007

The equivalent of PHP's explode and implode functions in Delphi

Whether you are using Delphi to work with files, do advanced string manipulation, or even webserver modules you will find out sooner or later that you need a function similar to PHP's Explode function. There are quite a few people out there that made special functions for this, but as it turns out, Delphi has its own way to sort this out (and by the way, it's FASTER).
The classes unit contains the TStringList type which facilitate the manipulation of strings.
It has two properties that will help you: Delimiter and CommaText.
How do they work? The type of the Delimiter property is char, while CommaText is string.
The Delimiter property can be set to almost any printable ASCII character but usually it's good to stick to the basics (tabs, commas, dash, slash, etc). How does it work? Lets presume you set the Delimiter property to '/' and the text you want to explode is "20/Feb/2007/23:37 PM". All you have to do now is set the CommaText property to the text you have.
Once you do this, the Strings array of the TStringList will be populated with "20", "Feb", "2007" and "23:37 PM" strings. All you have to remember is to set the Delimiter property to the character you want to explode the string by. So to split "foo,bar,foo2,bar2" set the Delimiter to ","; for "foo|bar|foo2|bar2" set it to "|" and so on.
And now, for the code:
uses Classes, System;
type StringArray: Array of String;

//other declarations and such

function explode(TextDelimiter:char; Text:String):StringArray;
var strList: TStringList;
i: Integer;
begin
strList := TStringList.Create;
strList.Delimiter := TextDelimiter;
strList.CommaText := Text;
for i:=0 to strList.count - 1 do
begin
SetLength(Result, i+1);
Result[i]:= strList.Strings[i];
end;
strList.Free;
end;
And how to use it:
procedure TForm1.Button1Click(Sender:TObject);
var exploded: StringArray;
i: Integer;
begin
exploded:= explode('/', '20/Feb/2007/23:37 PM');
for i:=0 to Length(exploded) - 1 do
Memo1.Lines.Add(exploded[i]);
end;
To implode a string, use the reverse process. Just populate the TStringList (using the Add method) and set the Delimiter property and after that, the CommaText property will contain your imploded string.