Alexandre Leclerc wrote:
> I checked arround to see if there was a function to parse a valid CSV
> string and return the result in a array?
>
> procedure DecodeCSV(s: string; var a: array of string);
>
> So a string like:
> 123, my name, "name, my", "just ""more"" text"
>
> would return in an array:
> [ '123' , 'my name' , 'name, my', 'just "more" text' ]
>
Maybe this will help.  It's probably pretty nasty code so I should be
embarrassed for posting it.  It does work for me however.

Instead of returning an array, I ask for a specific field position,
providing the complete CSV line, and it returns the contents of the
field.  It also is able to detect if a field was too small - something
specific to my project that could be removed (ala ShortFields.)  This
assumes the American / Microsloth method of comma-quote delimited which
I've recently learned is not all that standard.

It also won't handle lines greater than 500 characters by design... so
keep that in mind.

function GetField(AData: String; AField: Integer; var shortfields:
Boolean): String;
var
  TempStr: String;
  Quote1Pos, Quote2Pos, SepPos: Integer;
begin
  // give a field number, return the contents
  ShortFields := False;
  TempStr := AData;
  while AField > 0 do begin
    // skip over a field...
    if copy(TempStr,1,1) = '"' then begin
      TempStr := copy(TempStr,2,500); // drop the quote
      TempStr := copy(TempStr,pos('"', TempStr)+1,500); // drop to the
next quote
    end;
    TempStr := copy(TempStr,pos(',',TempStr)+1,500);
    AField := AField - 1;
    if length(TempStr) < 2 then begin
      shortfields := True;
      result := '';
      exit;
    end;
  end;
  // grab the data...
  if copy(TempStr,1,1) = '"' then begin
    TempStr := copy(TempStr,2,500); // drop quote
    TempStr := copy(TempStr,1,pos('"',TempStr)-1);
  end else begin
    TempStr := copy(TempStr,1,pos(',',TempStr)-1);
  end;
  Result := TempStr;
end;     

_________________________________________________________________
     To unsubscribe: mail [EMAIL PROTECTED] with
                "unsubscribe" as the Subject
   archives at http://www.lazarus.freepascal.org/mailarchives

Reply via email to