Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - Split string by line break

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.
like image 644
Josh Line Avatar asked Feb 18 '23 07:02

Josh Line


1 Answers

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;
like image 105
Sertac Akyuz Avatar answered Feb 28 '23 10:02

Sertac Akyuz