Is there a simple way in delphi to convert an array of strings to a tstringlist?
delphi array of string stringlist conversion
Asked Answered
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.
The latest update works well on all versions of Delphi, even those that don't have dynamic arrays (!) –
Hellraiser
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;
@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). –
Mcmanus
one comment: an open array parameter rather than a dynamic array gives the caller more flexibility with no cost. –
Hellraiser
@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. –
Mcmanus
With recent Delphi version you can call "addStrings" method of a TStrings and TstringList classes like this:
function StringListFromStrings(const Strings: array of string): TStringList;
var
i: Integer;
begin
Result := TStringList.Create;
Result.addStrings(Strings);
end;
Yuo can find documentation about this method at: https://docwiki.embarcadero.com/Libraries/Sydney/en/System.Classes.TStrings.AddStrings
© 2022 - 2024 — McMap. All rights reserved.
type TStringArray = array of string
, and is used asSA := TStringArray.Create('One', 'Two', Three');
and the TStringList.AddStrings is called asSL.AddStrings(SA);
– Mcmanus