Arūnas Liuiza

Vizitinė kortelė internete

Explode function for Delphi/Lazarus

PHP has a nice function Explode, that divides string into several smaller strings using some symbol as a divider: for example string ‘Cats|Dogs|Cows|Horses’ can be exploded to array(’Cats’,’Dogs’,’Cows’,’Horses’);
Today I wrote a similar function for my Lazarus project. If someone needs it:


function Explode(S, Bomb: String): TStrings;
var i : integer;
p : string;
begin
result := TstringList.Create;
while Pos(Bomb,s)<> 0
do begin
p := ‘’;
for i := 1 to Pos(Bomb,s)-1
do p := p + s[i];
result.Add(p);
Delete(s,1,Pos(Bomb,s));
end;
result.Add(s);
end;

Arūnas Liuiza, 2005-06-04 01:44

3 Responses to “Explode function for Delphi/Lazarus”

  1. Maloupi says:

    Thank you !
    I modified the delete ligne so it can work with bomb longer than 1 character :
    Delete(s,1,Pos(Bomb,s) + Length(Bomb)-1);

  2. Hello
    Thanks for this function! I needed it.
    The function does not work correctly for empty string argument S.
    The function then adds to the output an empty string – it’s OK.
    But then the number of outputs (TStrings.Count) is not 0 but 1.
    I fixed it.
    Last line: result.Add(s); I exchanged: if (Length(s) 0) then result.Add(s);
    regards
    M.P.

  3. Sorry
    CORRECTION:
    Characters more and minor (<>) dropped from the code above :-(


    Last line: result.Add(s); I exchanged: if (Length(s) <> 0) then result.Add(s);

    regards
    M.P.

Leave a Reply