program SplitStringDemo;
{$mode objfpc}{$H+}
uses
Classes;
{**
* Splits a multi-line string into individual lines using TStringList.
* Automatically handles both Unix (LF) and Windows (CRLF) line endings.
*
* @param inputStr The source string to split (passed as const for safety).
* @return A TStringList containing the parsed lines.
* Note: The caller is responsible for freeing the returned TStringList.
*}
function SplitByNewline(const inputStr: string): TStringList;
var
sList: TStringList;
begin
sList := TStringList.Create;
try
{ Assigning the string to Text automatically parses it line by line,
handling #10 and #13#10 transparently across platforms. }
sList.Text := inputStr;
Result := sList;
except
sList.Free;
raise;
end;
end;
var
textData: string;
lines: TStringList;
i: Integer;
begin
// Sample multi-line string containing mixed/Windows line breaks
textData := 'Hello Free Pascal!'#13#10'This is line two.'#10'Final line here.';
Writeln('--- Splitting String by Newline ---');
lines := SplitByNewline(textData);
try
for i := 0 to lines.Count - 1 do
begin
Writeln('Line ', i + 1, ': ', lines[i]);
end;
finally
// Always free TStringList instances to prevent memory leaks
lines.Free;
end;
end.
{
run:
Line 1: Hello Free Pascal!
Line 2: This is line two.
Line 3: Final line here.
}