I just need to split a string like: "STANS", "Payment, chk#1", ,1210.000
into an array based on ,
. The result in the string list would be
STANS
Payment, chk#1
1210.000
Create a TStringList
and assign your comma separated string to StringList.CommaText
. This parses your input and returns the split strings as the items of the string list.
StringList.CommaText := '"STANS", "Payment, chk# 1", ,1210.000';
//StringList[0]='STANS'
//StringList[1]='Payment, chk# 1'
//etc.
I wrote this function and works perfect for me in Delphi 2007
function ParseCSV(const S: string; ADelimiter: Char = ','; AQuoteChar: Char = '"'): TStrings;
type
TState = (sNone, sBegin, sEnd);
var
I: Integer;
state: TState;
token: string;
procedure AddToResult;
begin
if (token <> '') and (token[1] = AQuoteChar) then
begin
Delete(token, 1, 1);
Delete(token, Length(token), 1);
end;
Result.Add(token);
token := '';
end;
begin
Result := TstringList.Create;
state := sNone;
token := '';
I := 1;
while I <= Length(S) do
begin
case state of
sNone:
begin
if S[I] = ADelimiter then
begin
token := '';
AddToResult;
Inc(I);
Continue;
end;
state := sBegin;
end;
sBegin:
begin
if S[I] = ADelimiter then
if (token <> '') and (token[1] <> AQuoteChar) then
begin
state := sEnd;
Continue;
end;
if S[I] = AQuoteChar then
if (I = Length(S)) or (S[I + 1] = ADelimiter) then
state := sEnd;
end;
sEnd:
begin
state := sNone;
AddToResult;
Inc(I);
Continue;
end;
end;
token := token + S[I];
Inc(I);
end;
if token <> '' then
AddToResult;
if S[Length(S)] = ADelimiter then
AddToResult
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With