Converting TStringlist to string with delimiter
Asked Answered
E

3

18

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?

Equilibrist answered 16/7, 2013 at 8:6 Comment(5)
TStringList has a CommaText PropertyCigarillo
As JamesB wrote, there is CommaText property, but using Trim() should fix your original solution ie StringReplace(Trim(sl.Text), ...)Lush
@JamesB, CommaText surrounds the items with " as QuoteChar, maybe this is not what the OP wantsZachar
@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.Mutable
@UweRaabe, indeed it only quotes strings with spaces and quotes, but maybe it is not desired.Zachar
H
26

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.

Hereinafter answered 16/7, 2013 at 8:9 Comment(0)
Z
20

use the DelimitedText property:

channelList.Delimiter := ',';
channelList.QuoteChar := ''; // or
channelList.QuoteChar := #0; // for higher delphi versions
aCurrentChannel := channelList.DelimitedText;
Zachar answered 16/7, 2013 at 8:9 Comment(3)
channelList.QuoteChar := ''; does not work anymore, channelList.QuoteChar := #0; - its workingRandeerandel
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?Randeerandel
Indeed, seems Char type doesn't allow '' but needs #0 in Delphi 11. I consider it counter-intuitive though, will file a report for it at quality.embarcadero.comOrcutt
S
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(',');
Spence answered 16/7, 2013 at 9:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.