Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split the string in delphi

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
like image 812
suresh Avatar asked Jun 10 '11 04:06

suresh


2 Answers

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.
like image 106
David Heffernan Avatar answered Sep 19 '22 14:09

David Heffernan


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;
like image 30
FLICKER Avatar answered Sep 17 '22 14:09

FLICKER