如何在delphi中拆分字符串

时间:2011-06-10 04:26:36

标签: delphi delphi-2010

我只需将类似"STANS", "Payment, chk#1", ,1210.000的字符串拆分为基于,的数组。字符串列表中的结果为

STANS  
Payment, chk#1  

1210.000

2 个答案:

答案 0 :(得分:12)

创建TStringList并将逗号分隔的字符串分配给StringList.CommaText。这将解析您的输入并将拆分字符串作为字符串列表的项目返回。

StringList.CommaText := '"STANS", "Payment, chk# 1", ,1210.000';
//StringList[0]='STANS'
//StringList[1]='Payment, chk# 1'
//etc.

答案 1 :(得分:1)

我编写了这个函数,在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;