Search code examples
delphisplitdelphi-7tstringlist

Split string by multiple characters in Delphi 7


I want to know how to split a string with multiple characters in Deplhi 7. I know how to split a string with one character:

strlst := TStringList.Create;
strlst.Delimiter := '^';
strlst.DelimitedText := receivedtext;

And this is how I can split a string in Delphi XE7 with multiple characters.

strlst := tstringlist.create;
strlst.LineBreak := '<>';
strlst.Text := receivedtext;

But Delphi 7 doesn't have the LineBreak method. Is there another way to split a string by multiple characters?


Solution

  • You have the source code for XE7 so you can simply use the same method as it does in Delphi 7. It might look like this:

    procedure SetStringsText(Strings: TStrings; const Text, LineBreak: string);
    var
      P, Start, LB: PChar;
      S: string;
      LineBreakLen: Integer;
    begin
      Strings.BeginUpdate;
      try
        Strings.Clear;
        LineBreakLen := Length(LineBreak);
        P := PChar(Text);
        while P^ <> #0 do
        begin
          Start := P;
          LB := AnsiStrPos(P, PChar(LineBreak));
          while (P^ <> #0) and (P <> LB) do Inc(P);
          SetString(S, Start, P - Start);
          Strings.Add(S);
          if P = LB then
            Inc(P, LineBreakLen);
        end;
      finally
        Strings.EndUpdate;
      end;
    end;