delphisplitnewlineline-breaksdelphi-2006

Delphi (2006): how to Split by new line and break at the same time


I have this simple operation in Java, where the string is split by new line and break.

String i= "Holidays 
    
           Great. 
           Bye";
String []linesArray = i.split("\\r?\\n");

I would like to obtain the same result in Delphi 2006.

Is it valid to use the following steps?

charArray[0] := '\\r';
charArray[1] := '\\n';

strArray     := strA.Split(charArray);

Solution

  • I interpret your request like this: "Split a string at both CR and LF." which implies that CR+LF gives an empty string element. For instance, 'alpha'#13'beta'#10'gamma'#13#10'delta' yields the five elements 'alpha', 'beta', 'gamma', '', and 'delta'.

    If so, and if you are using a non-ancient version of Delphi, this is really simple:

    var S := 'alpha'#13'beta'#10'gamma'#13#10'delta';
    
    var Parts := S.Split([#13, #10]);
    for var Part in Parts do
      ShowMessage(Part);
    

    For old Delphi versions

    The code above requires TStringHelper (crucially) and also makes use of inline variable declarations, for in loops, and generics.

    For old Delphi versions, you can do it manually:

    type
      TStringArray = array of string;
    
    function Split(const S: string): TStringArray;
    var
      Count: Integer;
    const
      Delta = 512;
    
      procedure Add(const Part: string);
      begin
        if Length(Result) = Count then
          SetLength(Result, Length(Result) + Delta);
        Result[Count] := Part;
        Inc(Count);
      end;
    
    var
      p, i: Integer;
    
    begin
    
      Result := nil;
      Count := 0;
    
      p := 0; // previous delim
      for i := 1 to Length(S) do
        if S[i] in [#13, #10] then
        begin
          Add(Copy(S, Succ(p), i - p - 1));
          p := i;
        end;
    
      Add(Copy(S, Succ(p)));
    
      SetLength(Result, Count);
    
    end;
    
    procedure TForm1.FormCreate(Sender: TObject);
    var
      S: string;
      Parts: TStringArray;
      i: Integer;
    begin
    
      S := 'alpha'#13'beta'#10'gamma'#13#10'delta';
    
      Parts := Split(S);
      for i := 0 to High(Parts) do
        ShowMessage(Parts[i]);
    
    end;