Peter Martin's Delphi Tips

Parsing a Comma- or Tab-delimited String

and Extracting the N'th Field

This first procedure shows how to parse a delimited string into separate sub-strings:
procedure ParseStringToList (S : string);
var
  SL : TStringList;
begin
  SL:= TStringList.Create;
  with SL do
    try
      CommaText:= S;
      // do something with fields in SL Strings array
    finally
      Free;
      end;
end;
For example, to extract the N'th field from a delimited string:

function ExtractField (const S : string; N : word) : string; 
  // extract N'th field from tab- or comma-delimited string S; 
  // first field is #0
var
  SL : TStringList;
begin 
  Result:= ''; 
  SL:= TStringList.Create; 
  with SL do 
    try 
      CommaText:= S; 
      if Count > N then 
        Result:= Strings[N]; 
    finally 
      Free; 
    end; 
end;

Note: If a sub- string in S includes spaces or commas, it must be enclosed in double-quotes, as in:

String1,"S t r i n g 2",...,StringN