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);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.
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;