Reputation: 5158
TStringList.Delimiter is a TChar. This make it possible to have Delimitertext as
Test,Test,Test,Test
But I want to have ' and ' as Delimiter with the result
Test and Test and Test and Test
Of course I can solve it like this
s := List[0];
for i := 1 to List.Count - 1 do
s := s + ' and ' + List[i];
But it would be more elegant to do
List.Delimiter := ' and ';
s := List.DelimiterText;
So I try this code to override TStringList;
unit Unit5;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Menus, StdCtrls, cxButtons, cxTextEdit,
cxMemo;
type
TForm5 = class(TForm)
cxMemo1: TcxMemo;
cxButton1: TcxButton;
procedure cxButton1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TAttracsStringList = class(TStringList)
private
FDelimiter: String;
procedure SetDelimiter(const Value: String);
function GetDelimiter: String;
public
property Delimiter: String read GetDelimiter write SetDelimiter;
end;
var
Form5: TForm5;
implementation
{$R *.dfm}
function TAttracsStringList.GetDelimiter: String;
begin
Result := FDelimiter;
end;
procedure TAttracsStringList.SetDelimiter(const Value: String);
begin
FDelimiter := Value;
end;
procedure TForm5.cxButton1Click(Sender: TObject);
var
vList: TAttracsStringList;
i: Integer;
begin
vList := TAttracsStringList.Create;
try
vList.Delimiter := ' and ';
for i := 0 to 3 do
vList.Add('Test');
cxMemo1.Text := vList.DelimitedText;
finally
vList.Free;
end;
end;
end.
It don't work. The memo got result
Test,Test,Test,Test
How can I fix this ?
Edit I see now that GetDelimiter and SetDelimiter is private in TStringList. So I cannot override them. Wonder if there is a way to achieve what I want ?
Edit2 I solved it by add
property DelimitedText: String read GetDelimitedText;
with method
function TAttracsStringList.GetDelimitedText: String;
var
i: Integer;
begin
if Count > 0 then
begin
Result := Strings[0];
for i := 1 to Count - 1 do
Result := Result + Delimiter + Strings[i];
end
else
Result := '';
end;
So if someone don't have a more clever way I consider this as solved.
Upvotes: 1
Views: 1003
Reputation: 47714
There is indeed another solution:
lst := TStringList.Create;
try
for I := 1 to 4 do
lst.Add('Test');
lst.LineBreak := ' and ';
Writeln(lst.Text);
finally
lst.Free;
end;
As a drawback the individual entries are not quoted.
Upvotes: 4