15

I have a list of strings stored in TStringList, i want to convert it into string seperated by commas and i use the following code

channelList: TStringList;
aCurrentChannel :=  Stringreplace(channelList.Text,Char(13)+Char(10),',',[rfReplaceAll]);

but the last character is coming as , like 1,2, is there anyway to avoid that?

Cœur
  • 32,421
  • 21
  • 173
  • 232
Jeeva
  • 4,329
  • 2
  • 28
  • 55
  • 6
    TStringList has a CommaText Property – James Barrass Jul 16 '13 at 08:07
  • As JamesB wrote, there is `CommaText` property, but using `Trim()` should fix your original solution ie `StringReplace(Trim(sl.Text), ...)` – ain Jul 16 '13 at 08:10
  • @JamesB, CommaText surrounds the items with " as QuoteChar, maybe this is not what the OP wants – whosrdaddy Jul 16 '13 at 08:15
  • @whosrdaddy, QuoteChar is only used when needed (i.e. when blanks or quotes are found in the strings). Nevertheless, DelimitedText acts the same way concerning quotes. CommaText only uses fixed characters for Delimiter and QuoteChar. – Uwe Raabe Jul 16 '13 at 08:49
  • @UweRaabe, indeed it only quotes strings with spaces and quotes, but maybe it is not desired. – whosrdaddy Jul 16 '13 at 09:02

3 Answers3

21

You need to use the DelimitedText property of the TStringList class. From the online help

Use DelimitedText to get or set all the strings in the TStrings object in a single string, separated by the character specified by the Delimiter property.

Sir Rufo
  • 16,671
  • 2
  • 33
  • 66
RBA
  • 11,762
  • 14
  • 72
  • 118
16

use the DelimitedText property:

channelList.Delimiter := ',';
channelList.QuoteChar := ''; // or
channelList.QuoteChar := #0; // for higher delphi versions
aCurrentChannel := channelList.DelimitedText;
whosrdaddy
  • 11,297
  • 4
  • 41
  • 92
  • `channelList.QuoteChar := '';` does not work anymore, `channelList.QuoteChar := #0;` - its working – Roman Marusyk Dec 29 '15 at 13:37
  • I'm using XE7 and I got an error: E2010 Incompatible types: 'Char' and 'string'. But in Delphi 6 I always used `QuoteChar:= '';` It depends on unicode? – Roman Marusyk Dec 29 '15 at 19:14
1

While you're into string lists i suggest you to cast a look at http://wiki.delphi-jedi.org/wiki/JCL_Help:IJclStringList

// var channelList: iJclStringList;
var s: string;

s := JclStringList.Add(['aaa','bbb','ccc '])
         .Split('ddd: eee', ':', False).Trim.Join(',');
Arioch 'The
  • 15,005
  • 31
  • 59