string 根据分隔符将字符串拆分为字符串数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2625707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:42:03  来源:igfitidea点击:

Split a string into an array of strings based on a delimiter

delphistringsplitdelimiter

提问by Ryan

I'm trying to find a Delphi function that will split an input string into an array of strings based on a delimiter. I've found a lot on Google, but all seem to have their own issues and I haven't been able to get any of them to work.

我正在尝试找到一个 Delphi 函数,该函数将基于分隔符将输入字符串拆分为字符串数组。我在谷歌上找到了很多,但似乎都有自己的问题,我无法让其中任何一个工作。

I just need to split a string like: "word:doc,txt,docx"into an array based on ':'. The result would be ['word', 'doc,txt,docx'].

我只需要将像:这样的字符串拆分为 "word:doc,txt,docx"基于 ':' 的数组。结果是 ['word', 'doc,txt,docx']

Does anyone have a function that they know works?

有没有人有他们知道有效的功能?

Thank you

谢谢

回答by RRUZ

you can use the TStrings.DelimitedText property for split an string

您可以使用 TStrings.DelimitedText 属性来拆分字符串

check this sample

检查这个样本

program Project28;

{$APPTYPE CONSOLE}

uses
  Classes,
  SysUtils;

procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ;
begin
   ListOfStrings.Clear;
   ListOfStrings.Delimiter       := Delimiter;
   ListOfStrings.StrictDelimiter := True; // Requires D2006 or newer.
   ListOfStrings.DelimitedText   := Str;
end;


var
   OutPutList: TStringList;
begin
   OutPutList := TStringList.Create;
   try
     Split(':', 'word:doc,txt,docx', OutPutList) ;
     Writeln(OutPutList.Text);
     Readln;
   finally
     OutPutList.Free;
   end;
end.

UPDATE

更新

See this linkfor an explanation of StrictDelimiter.

有关的解释,请参阅此链接StrictDelimiter

回答by NGLN

There is no need for engineering a Splitfunction. It already exists, see: Classes.ExtractStrings.

无需设计Split功能。它已经存在,请参阅:Classes.ExtractStrings

Use it in a following manner:

按以下方式使用它:

program Project1;

{$APPTYPE CONSOLE}

uses
  Classes;

var
  List: TStrings;
begin
  List := TStringList.Create;
  try
    ExtractStrings([':'], [], PChar('word:doc,txt,docx'), List);
    WriteLn(List.Text);
    ReadLn;
  finally
    List.Free;
  end;
end.

And to answer the question fully; Listrepresents the desired array with the elements:

并完整回答问题;List用元素表示所需的数组:

List[0] = 'word'
List[1] = 'doc,txt,docx'

回答by alex

You can use StrUtils.SplitString.

您可以使用StrUtils.SplitString.

function SplitString(const S, Delimiters: string): TStringDynArray;

Its description from the documentation:

它来自文档的描述:

Splits a string into different parts delimited by the specified delimiter characters.

SplitStringsplits a string into different parts delimited by the specified delimiter characters. Sis the string to be split. Delimitersis a string containing the characters defined as delimiters.

SplitStringreturns an array of strings of type System.Types.TStringDynArraythat contains the split parts of the original string.

将字符串拆分为由指定分隔符分隔的不同部分。

SplitString将字符串拆分为由指定分隔符字符分隔的不同部分。S是要拆分的字符串。 Delimiters是一个包含定义为分隔符的字符的字符串。

SplitString返回System.Types.TStringDynArray类型的字符串数组,其中包含原始字符串的拆分部分。

回答by LU RD

Using the SysUtils.TStringHelper.Splitfunction, introduced in Delphi XE3:

使用SysUtils.TStringHelper.Split功能,在Delphi XE3介绍:

var
  MyString: String;
  Splitted: TArray<String>;
begin
  MyString := 'word:doc,txt,docx';
  Splitted := MyString.Split([':']);
end.

This will split a string with a given delimiter into an array of strings.

这会将具有给定分隔符的字符串拆分为字符串数组。

回答by Frank

I always use something similar to this:

我总是使用类似的东西:

Uses
   StrUtils, Classes;

Var
  Str, Delimiter : String;
begin
  // Str is the input string, Delimiter is the delimiter
  With TStringList.Create Do
  try
    Text := ReplaceText(S,Delim,#13#10);

    // From here on and until "finally", your desired result strings are
    // in strings[0].. strings[Count-1)

  finally
    Free; //Clean everything up, and liberate your memory ;-)
  end;

end;

回答by Deltics

Similar to the Explode()function offered by Mef, but with a couple of differences (one of which I consider a bug fix):

类似于Mef 提供的Explode()函数,但有一些不同(我认为其中一个是错误修复):

  type
    TArrayOfString = array of String;


  function SplitString(const aSeparator, aString: String; aMax: Integer = 0): TArrayOfString;
  var
    i, strt, cnt: Integer;
    sepLen: Integer;

    procedure AddString(aEnd: Integer = -1);
    var
      endPos: Integer;
    begin
      if (aEnd = -1) then
        endPos := i
      else
        endPos := aEnd + 1;

      if (strt < endPos) then
        result[cnt] := Copy(aString, strt, endPos - strt)
      else
        result[cnt] := '';

      Inc(cnt);
    end;

  begin
    if (aString = '') or (aMax < 0) then
    begin
      SetLength(result, 0);
      EXIT;
    end;

    if (aSeparator = '') then
    begin
      SetLength(result, 1);
      result[0] := aString;
      EXIT;
    end;

    sepLen := Length(aSeparator);
    SetLength(result, (Length(aString) div sepLen) + 1);

    i     := 1;
    strt  := i;
    cnt   := 0;
    while (i <= (Length(aString)- sepLen + 1)) do
    begin
      if (aString[i] = aSeparator[1]) then
        if (Copy(aString, i, sepLen) = aSeparator) then
        begin
          AddString;

          if (cnt = aMax) then
          begin
            SetLength(result, cnt);
            EXIT;
          end;

          Inc(i, sepLen - 1);
          strt := i + 1;
        end;

      Inc(i);
    end;

    AddString(Length(aString));

    SetLength(result, cnt);
  end;

Differences:

区别:

  1. aMax parameter limits the number of strings to be returned
  2. If the input string is terminated by a separator then a nominal "empty" final string is deemed to exist
  1. aMax 参数限制要返回的字符串数量
  2. 如果输入字符串以分隔符结尾,则认为存在名义上的“空”最终字符串

Examples:

例子:

SplitString(':', 'abc') returns      :    result[0]  = abc

SplitString(':', 'a:b:c:') returns   :    result[0]  = a
                                          result[1]  = b
                                          result[2]  = c
                                          result[3]  = <empty string>

SplitString(':', 'a:b:c:', 2) returns:    result[0]  = a
                                          result[1]  = b

It is the trailing separator and notional "empty final element" that I consider the bug fix.

我认为修复了错误的是尾随分隔符和名义上的“空最终元素”。

I also incorporated the memory allocation change I suggested, with refinement (I mistakenly suggested the input string might at most contain 50% separators, but it could conceivably of course consist of 100% separator strings, yielding an array of empty elements!)

我还合并了我建议的内存分配更改,并进行了改进(我错误地建议输入字符串最多可能包含 50% 的分隔符,但可以想象它当然可以包含 100% 的分隔符字符串,从而产生一个空元素数组!)

回答by Delphi 7

Explode is very high speed function, source alhoritm get from TStrings component. I use next test for explode: Explode 134217733 bytes of data, i get 19173962 elements, time of work: 2984 ms.

Explode 是一个非常高速的函数,来源 alhoritm 来自 TStrings 组件。我使用下一个测试来进行爆炸:爆炸 134217733 字节的数据,我得到 19173962 个元素,工作时间:2984 毫秒。

Implode is very low speed function, but i write it easy.

内爆是非常低速的功能,但我写起来很容易。

{ ****************************************************************************** }
{  Explode/Implode (String <> String array)                                      }
{ ****************************************************************************** }
function Explode(S: String; Delimiter: Char): Strings; overload;
var I, C: Integer; P, P1: PChar;
begin
    SetLength(Result, 0);
    if Length(S) = 0 then Exit;
    P:=PChar(S+Delimiter); C:=0;
    while P^ <> #0 do begin
       P1:=P;
       while (P^ <> Delimiter) do P:=CharNext(P);
       Inc(C);
       while P^ in [#1..' '] do P:=CharNext(P);
       if P^ = Delimiter then begin
          repeat
           P:=CharNext(P);
          until not (P^ in [#1..' ']);
       end;
    end;
    SetLength(Result, C);
    P:=PChar(S+Delimiter); I:=-1;
    while P^ <> #0 do begin
       P1:=P;
       while (P^ <> Delimiter) do P:=CharNext(P);
       Inc(I); SetString(Result[I], P1, P-P1);
       while P^ in [#1..' '] do P:=CharNext(P);
       if P^ = Delimiter then begin
          repeat
           P:=CharNext(P);
          until not (P^ in [#1..' ']);
       end;
    end;
end;

function Explode(S: String; Delimiter: Char; Index: Integer): String; overload;
var I: Integer; P, P1: PChar;
begin
    if Length(S) = 0 then Exit;
    P:=PChar(S+Delimiter); I:=1;
    while P^ <> #0 do begin
       P1:=P;
       while (P^ <> Delimiter) do P:=CharNext(P);
        SetString(Result, P1, P-P1);
        if (I <> Index) then Inc(I) else begin
           SetString(Result, P1, P-P1); Exit;
        end;
       while P^ in [#1..' '] do P:=CharNext(P);
       if P^ = Delimiter then begin
          repeat
           P:=CharNext(P);
          until not (P^ in [#1..' ']);
       end;
    end;
end;

function Implode(S: Strings; Delimiter: Char): String;
var iCount: Integer;
begin
     Result:='';
     if (Length(S) = 0) then Exit;
     for iCount:=0 to Length(S)-1 do
     Result:=Result+S[iCount]+Delimiter;
     System.Delete(Result, Length(Result), 1);
end;

回答by Ihor Konovalenko

var  
    su  : string;        // What we want split
    si  : TStringList;   // Result of splitting
    Delimiter : string;
    ...
    Delimiter := ';';
    si.Text := ReplaceStr(su, Delimiter, #13#10);

Lines in silist will contain splitted strings.

在线路SI列表将包含劈裂字符串。

回答by bob_saginowski

You can make your own function which returns TArray of string:

您可以创建自己的函数,该函数返回字符串的 TArray:

function mySplit(input: string): TArray<string>;
var
  delimiterSet: array [0 .. 0] of char; 
     // split works with char array, not a single char
begin
  delimiterSet[0] := '&'; // some character
  result := input.Split(delimiterSet);
end;

回答by Ale? Oskar Kocur

I wrote this function which returns linked list of separated strings by specific delimiter. Pure free pascal without modules.

我编写了这个函数,它通过特定的分隔符返回分隔字符串的链表。没有模块的纯自由 pascal。

Program split_f;

type
    PTItem = ^TItem;
    TItem = record
        str : string;
        next : PTItem;
    end;

var
    s : string;
    strs : PTItem;

procedure split(str : string;delim : char;var list : PTItem);
var
    i : integer;
    buff : PTItem;
begin
    new(list);
    buff:= list;
    buff^.str:='';
    buff^.next:=nil;

    for i:=1 to length(str) do begin
        if (str[i] = delim) then begin
            new(buff^.next);
            buff:=buff^.next;
            buff^.str := '';
            buff^.next := nil;
        end
        else
        buff^.str:= buff^.str+str[i];
    end;
end;

procedure print(var list:PTItem);
var
    buff : PTItem;
begin
    buff := list;
    while buff<>nil do begin
        writeln(buff^.str);
        buff:= buff^.next;
    end;
end;

begin

    s := 'Hi;how;are;you?';

    split(s, ';', strs);
    print(strs);


end.