Split a string into an array of strings based on a delimiter

Ryan picture Ryan · Apr 12, 2010 · Viewed 256.7k times · Source

I'm trying to find a Delphi function that will split an input string into an array of strings based on a delimiter. I've found a lot on Google, but all seem to have their own issues and I haven't been able to get any of them to work.

I just need to split a string like: "word:doc,txt,docx" into an array based on ':'. The result would be ['word', 'doc,txt,docx'].

Does anyone have a function that they know works?

Thank you

Answer

RRUZ picture RRUZ · Apr 13, 2010

you can use the TStrings.DelimitedText property for split an string

check this sample

program Project28;

{$APPTYPE CONSOLE}

uses
  Classes,
  SysUtils;

procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ;
begin
   ListOfStrings.Clear;
   ListOfStrings.Delimiter       := Delimiter;
   ListOfStrings.StrictDelimiter := True; // Requires D2006 or newer.
   ListOfStrings.DelimitedText   := Str;
end;


var
   OutPutList: TStringList;
begin
   OutPutList := TStringList.Create;
   try
     Split(':', 'word:doc,txt,docx', OutPutList) ;
     Writeln(OutPutList.Text);
     Readln;
   finally
     OutPutList.Free;
   end;
end.

UPDATE

See this link for an explanation of StrictDelimiter.