Delphi 字符串拆分/分割[2] - Classes.ExtractStrings

Delphi 字符串拆分/分割[2] - Classes.ExtractStrings

原型:

function ExtractStrings(Separators, WhiteSpace: TSysCharSet; Content: PChar;
  Strings: TStrings): Integer;
var
  Head, Tail: PChar;
  EOS, InQuote: Boolean;
  QuoteChar: Char;
  Item: string;
begin
  Result := 0;
  if (Content = nil) or (Content^=#0) or (Strings = nil) then Exit;
  Tail := Content;
  InQuote := False;
  QuoteChar := #0;
  Strings.BeginUpdate;
  try
    repeat
      while Tail^ in WhiteSpace + [#13, #10] do Tail := StrNextChar(Tail);
      Head := Tail;
      while True do
      begin
        while (InQuote and not (Tail^ in [QuoteChar, #0])) or
          not (Tail^ in Separators + [#0, #13, #10, '''', '"']) do Tail := StrNextChar(Tail);
        if Tail^ in ['''', '"'] then
        begin
          if (QuoteChar <> #0) and (QuoteChar = Tail^) then
            QuoteChar := #0
          else if QuoteChar = #0 then
            QuoteChar := Tail^;
          InQuote := QuoteChar <> #0;
          Tail := StrNextChar(Tail);
        end else Break;
      end;
      EOS := Tail^ = #0;
      if (Head <> Tail) and (Head^ <> #0) then
      begin
        if Strings <> nil then
        begin
          SetString(Item, Head, Tail - Head);
          Strings.Add(Item);
        end;
        Inc(Result);
      end;
      Tail := StrNextChar(Tail);
    until EOS;
  finally
    Strings.EndUpdate;
  end;
end;

参数:

  • Separators  //分隔符,可以是多个,例如 [';',',',':'] 可以按分号、逗号、分号来同时分割。
  • WhiteSpace //开头被忽略字符,例如['<','>',' '],被分割出的字符,如果开头有大于号,小于号,或者分号,被分割出来后会被忽略。
  • Content   //被分割的字符串。
  • Strings   //返回字符串

返回值:

  分割出的字符串数量。

 

用法示例:

var 
    S:   string; 
    SL:   TStringList; 
begin 
    S := '222,777,888 '; 
    SL := TStringList.Create; 
    ExtractStrings([','],[],PChar(S),SL); 
    ShowMessage(SL.Text); 
    SL.Free; 
end; 
var
  s: String;
  List: TStringList;
begin
  s := 'delphi: #你好; #pascal, 程序';
  List := TStringList.Create;
  ExtractStrings([';',',',':'],['#',' '],PChar(s),List);  //第一个参数是分隔符; 第二个参数是开头被忽略的字符
  ShowMessage(List.Text);  
  List.Free;
end;

  

  

 

创建时间:2021.01.07  更新时间:

 

posted on 2021-01-07 10:34  滔Roy  阅读(481)  评论(0编辑  收藏  举报

导航