如何在delphi中分割字符串

问题描述

| 我只需要将像:0ѭ这样的字符串拆分为基于
,
的数组。字符串列表中的结果将是
STANS  
Payment,chk#1  

1210.000
    

解决方法

        创建一个
TStringList
,并将逗号分隔的字符串分配给
StringList.CommaText
。这将解析您的输入,并将拆分后的字符串作为字符串列表的项目返回。
StringList.CommaText := \'\"STANS\",\"Payment,chk# 1\",1210.000\';
//StringList[0]=\'STANS\'
//StringList[1]=\'Payment,chk# 1\'
//etc.
    ,        我编写了此函数,并且在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;