0
votes

I want to populate a TStringList and get a comma-delimited quoted result.

According to what I have read, it is possible, but I just get a comma-delimited result, no quotes. I cannot get it to drop duplicates.

procedure TForm5.BitBtn1Click(Sender: TObject);
var
  sl : TStringList;
  s : string;
begin
  sl := TStringList.Create;
  try
    sl.Delimiter := ',';
    sl.QuoteChar := '"';
    sl.Duplicates := dupIgnore;
    //sl.DelimitedText := '"1","2","3"';
    sl.DelimitedText := '1,2,3';
    sl.Add('a');
    sl.Add('2');
    s := sl.DelimitedText;
    ShowMessage(s);
  finally
    sl.Free;
  end;
end;

I keep getting var s set as 1,2,3,a,2, but I am expecting "1","2","3","a" instead.

2
You tagged this XE, but state that you are using XE7. Which is it? Please decide and make sure that the tagging and text are both correct. - David Heffernan
I changed the tag - Gerhard

2 Answers

1
votes

The TStrings.DelimitedText property getter wraps a string in the QuoteChar only when it contains either:

  1. the #0 null character.
  2. the QuoteChar character
  3. the Delimiter character
  4. if TStrings.StrictDelimiters is False, any ASCII whitespace/control characters between #1..#32, inclusive.

If you want the strings to always be quoted, you will have to quote them manually, eg:

procedure TForm5.BitBtn1Click(Sender: TObject);
var
  sl : TStringList;
  s, tmp : string;
  i: Integer;
begin
  sl := TStringList.Create;
  try
    sl.Delimiter := ',';
    sl.QuoteChar := '"';
    sl.Duplicates := dupIgnore;

    //sl.DelimitedText := '"1","2","3"';
    sl.DelimitedText := '1,2,3';

    sl.Add('a');
    sl.Add('2');

    //s := sl.DelimitedText;
    s := '';
    for I := 0 to sl.Count-1 do
      S := S + AnsiQuotedStr(sl[I], sl.QuoteChar) + sl.Delimiter;
    Delete(S, Length(S), 1);

    ShowMessage(s);
  finally
    sl.Free;
  end;
end;
0
votes

try this:

procedure TForm1.FormCreate(Sender: TObject);
var
  sl : TStringList;
  s : string;
begin
  sl := TStringList.Create;
  try
    sl.Delimiter := ',';
    sl.QuoteChar := #0;  // default = '"'
    sl.Duplicates := dupIgnore;
    sl.DelimitedText := '"1","2","3"';
    sl.Add('a');
    sl.Add('"2"');
    s := sl.DelimitedText;
    ShowMessage(s);
  finally
    sl.Free;
  end;
end;