Gerhard
Gerhard

Reputation: 81

Delphi XE7 TStrings.DelimitedText

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.

Upvotes: 2

Views: 1259

Answers (2)

user2964812
user2964812

Reputation:

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;

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 598114

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;

Upvotes: 1

Related Questions