Reputation: 4239
I want to add 30 different strings into a stringList . I do not want to add AList.Items.Add
30 times. Nor do i want to keep the strings in an array and run a loop. I was thinking may be i could write a single AList.Add
( not in a loop) where the strings to be added were seperated by a Delimiter .
e.g.
AList.Add('Data1' + <Delim> + 'Data2' ...)
How to do that ? Please note that i am just curious as to if it can be done this way. It is quite ok if not as there are better ways to accomplish this. ( keeping the strings in an array and using a loop to add data is my idea)
Thanks in Advance
Upvotes: 1
Views: 9822
Reputation: 596517
Create a temporary TStringList
, assign the string to its DelimitedText
property, pass the temporary to the AddStrings()
method of the destination TStringList
, and then free the temporary.
var
Temp: TStringList;
begin
Temp := TStringList.Create;
try
Temp.Delimiter := <Delim>;
// if using a Delphi version that has StrictDelimiter available:
// Temp.StrictDelimiter := True;
Temp.DelimitedText := 'Data1' + <Delim> + 'Data2' ...;
AList.AddStrings(Temp);
finally
Temp.Free;
end;
end;
Upvotes: 7
Reputation: 5545
Just use DelimitedText
property. E.g. if your delimiter is set to ,
(default in TStringList) then you can write this code:
AList.DelimitedText := 'Data1,Data2';
Upvotes: 6
Reputation: 3234
you can use TStringList.DelimitedText
property to add text, wich uses your Delimiter
char. TStringList
will split your text and then you can access each string separately using strings
property;
program Project3;
{$APPTYPE CONSOLE}
uses classes;
const DATA = 'one,two,three';
var sl : TStringList;
s : string;
begin
sl := TStringList.Create();
try
sl.Delimiter := ',';
sl.DelimitedText := DATA;
for s in sl do begin
writeln(s);
end;
readln;
finally
sl.Free();
end;
end.
and result is
one
two
three
Upvotes: 1
Reputation: 108963
You can write a procedure that does this:
procedure SLAddStrings(SL: TStrings; S: array of string);
var
i: Integer;
begin
SL.BeginUpdate;
for i := low(S) to high(S) do
SL.Add(S[i]);
SL.EndUpdate;
end;
Try it:
var
SL: TStringList;
begin
SL := TStringList.Create;
SLAddStrings(SL, ['car', 'cat', 'dog']);
Upvotes: 12