17

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

Brian Webster
  • 27,545
  • 47
  • 143
  • 218
xianghua
  • 173
  • 1
  • 1
  • 4

2 Answers2

14

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.

David Heffernan
  • 572,264
  • 40
  • 974
  • 1,389
  • 6
    Note that this only works in D2009 and up (where generics are available). The same type code in D2007 (which supports dynamic array constructor syntax) fails with "E2010 Incompatible types: 'TStrings' and 'TStringArray'", where `type TStringArray = array of string`, and is used as `SA := TStringArray.Create('One', 'Two', Three');` and the TStringList.AddStrings is called as `SL.AddStrings(SA);` – Ken White May 04 '11 at 17:42
  • The latest update works well on all versions of Delphi, even those that don't have dynamic arrays (!) – David Heffernan Dec 10 '12 at 15:10
9

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;
Ken White
  • 117,855
  • 13
  • 197
  • 405
  • @Warren: Thanks. Some of us are stuck using them because we have projects that have no need for Unicode support (in house apps in particular) and therefore can't justify the work to convert them to new versions of Delphi (and can't justify the expense of the new versions themselves because the powers-that-be don't care about Unicode or generics and such). – Ken White May 04 '11 at 18:00
  • one comment: an open array parameter rather than a dynamic array gives the caller more flexibility with no cost. – David Heffernan May 04 '11 at 21:59
  • @David: True. I was specifically addressing the OP's "array of string", which seemed to me to be a reference to a dynamic array. @Warren: Not to say I'm not familiar with newer Delphi versions. :) I have XE; just don't get to use it as much as I'd like, as I have 40+ apps currently in D2007 that probably won't get updated to Unicode anytime in the near future. – Ken White May 05 '11 at 01:44