Title: Quick and Dirty CSV file parsing
Question: Sometimes you dont need fancy parsing classes- reading a CSV file line by line is one such case. The Tstrings/Tstringlist classes have a property that will do this for you.
Answer:
The Tstrings/TStringlist classes have the commatext property which allows you to assign a string full of comma separated items and have them automatically separated.
This example shows how to read in a CSV file and when you come to process the line of text, it has been separated in ts.count strings thus making it easy to process.
Var ts : tstringlist;
S : string;
Tf : Textfile;
Begin
Ts := Tstringlist.create;
Assignfile(tf,filename);
Reset(tf);
While not eof(tf) do
Begin
Readln(tf,S);
Ts.CommaText := S;
//ProcessLine;
end;
closefile(tf);
ts.free;
end;
You can do this in reverse as well, take a stringlist and create a single line of items all comma separated.
Commatext also handles strings and commas by accepting double quotes around items. It will take both 1,2,3,4 and "1","2","3","4"
although "1","2,3","4" would give only three items as commas inside double quotes are ignored. To include quotes in strings, put them in twice like this "1",""2" which produces items 1 and "2