Delphi - Split string by line break
Asked Answered
L

1

5

Note: I am using Delphi 7.

Is there a way to split a string by a line break?

I would like something like the following:

procedure Split
   (const Delimiter: Char;
    Input: string;
    const Strings: TStrings) ;
begin
   Assert(Assigned(Strings)) ;
   Strings.Clear;
   Strings.Delimiter := Delimiter;
   Strings.DelimitedText := Input;
end;

var
  xMSG:String;
  xStr:String;
  xStrList:TStrings;
  xLineBreak:String;
  xHello:String;
  xWorld:String;
begin
  xLineBreak := AnsiString(#13#10);
  xMSG := 'Hello ' + xLineBreak + 'World';
  xStrList := TStringList.Create;
  Split(xLineBreak,AnsiString(xMSG),xStrList);
  xHello := xStrList[0];
  xWorld := xStrList[1];
  MessageBox(0,PAnsiChar(xHello + xWorld),'Test',0);
end.
Lagos answered 2/12, 2012 at 8:31 Comment(0)
M
10

Yes, this is what the Text property does. Quote from the help (Text property (TStrings)):

Lists the strings in the TStrings object as a single string with the individual strings delimited by carriage returns and line feeds.

Since it would be a one liner, you don't need an additional utility procedure.

var
  xMSG:String;
//  xStr:String;
  xStrList:TStrings;
//  xLineBreak:String;
  xHello:String;
  xWorld:String;
begin
//  xLineBreak := AnsiString(#13#10);     // you don't need this, there's sLineBreak
  xMSG := 'Hello ' + sLineBreak + 'World';
  xStrList := TStringList.Create;

//  Split(xLineBreak,AnsiString(xMSG),xStrList);  
  xStrList.Text := xMSG;  // <--

  xHello := xStrList[0];
  xWorld := xStrList[1];
  xStrList.Free;
  MessageBox(0,PAnsiChar(xHello + xWorld),'Test',0);
end;
Major answered 3/12, 2012 at 2:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.