program WrapTextProgram;
{$mode objfpc}{$H+}{$J-}
{
This program wraps a string into lines of maximum width `w`.
Method:
- Use TStringList to split the input text into words.
- Build each line until adding another word would exceed the width.
- When the limit is reached, store the line and begin a new one.
- Uses standard string operations (Length, concatenation) for clarity.
}
uses
SysUtils, Classes;
function WrapText(const S: string; W: Integer): string;
var
WordList: TStringList;
Line, ResultText, Temp: string;
I: Integer;
begin
{ Create a TStringList to hold words }
WordList := TStringList.Create;
try
WordList.Delimiter := ' ';
WordList.StrictDelimiter := True;
WordList.DelimitedText := S;
Line := '';
ResultText := '';
{ Build wrapped lines from words in WordList }
for I := 0 to WordList.Count - 1 do
begin
Temp := WordList[I];
{ If line is empty, start it with the word }
if Line = '' then
Line := Temp
else
begin
{ Check if adding the next word exceeds width }
if Length(Line) + 1 + Length(Temp) <= W then
Line := Line + ' ' + Temp
else
begin
{ Store the completed line }
ResultText := ResultText + Line + LineEnding;
Line := Temp;
end;
end;
end;
{ Add the final line }
if Line <> '' then
ResultText := ResultText + Line;
Result := ResultText;
finally
WordList.Free;
end;
end;
var
Sample, Wrapped: string;
begin
Sample :=
'Free Pascal provides useful built-in functions for handling strings. ' +
'This program demonstrates how to wrap text cleanly and efficiently.';
Wrapped := WrapText(Sample, 35);
WriteLn(Wrapped);
end.
{
run:
Free Pascal provides useful
built-in functions for handling
strings. This program demonstrates
how to wrap text cleanly and
efficiently.
}