Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delphi array of string stringlist conversion

Is there a simple way in delphi to convert an array of strings to a tstringlist?

like image 215
xianghua Avatar asked May 04 '11 16:05

xianghua


2 Answers

Once you have created the string list, you can simply call AddStrings().

Or for older versions of Delphi that do not support the AddStrings() overloads that accept arrays, you can roll your own.

function StringListFromStrings(const Strings: array of string): TStringList;
var
  i: Integer;
begin
  Result := TStringList.Create;
  for i := low(Strings) to high(Strings) do
    Result.Add(Strings[i]);
end;

Using an open array parameter affords the maximum flexibility for the caller.

like image 182
David Heffernan Avatar answered Nov 12 '22 10:11

David Heffernan


For pre-generic versions of Delphi, you can use something like this:

type
  TStringArray = array of string;

procedure StringListFromStrings(const StringArray: TStringArray; 
  const SL: TStringList);
var
  // Versions of Delphi supporting for..in loops
  s: string;

  // Pre for..in version
  // i: Integer;
begin
  // TStringList should be created and passed in, so it's clear
  // where it should be free'd.
  Assert(Assigned(SL));

  // Delphi versions with for..in support
  for s in StringArray do
    SL.Add(s);

  // Pre for..in versions
  // for i := Low(StringArray) to High(StringArray) do
  //   SL.Add(StringArray[i]);
end;
like image 22
Ken White Avatar answered Nov 12 '22 11:11

Ken White