How to format an array of strings in lines with maxWidth without breaking the words in Pascal

1 Answer

0 votes
program WordWrap;

const
  MaxWords = 100;
  MaxLines = 100;

type
  TStringArray = array[1..MaxWords] of string;
  TLineArray   = array[1..MaxLines] of string;

procedure FormatLines(var words: TStringArray; wordCount, maxWidth: integer;
                      var lines: TLineArray; var lineCount: integer);
var
  currentLine: string;
  currentLength: integer;
  i, wordLen, spaceNeeded: integer;
begin
  lineCount := 0;
  currentLine := '';
  currentLength := 0;

  for i := 1 to wordCount do
  begin
    wordLen := Length(words[i]);

    { Determine if we need a space before the next word }
    if currentLine <> '' then
      spaceNeeded := 1
    else
      spaceNeeded := 0;

    { If adding this word exceeds maxWidth, push current line }
    if currentLength + spaceNeeded + wordLen > maxWidth then
    begin
      if currentLine <> '' then
      begin
        Inc(lineCount);
        lines[lineCount] := currentLine;
      end;
      currentLine := words[i];
      currentLength := wordLen;
    end
    else
    begin
      if currentLine <> '' then
      begin
        currentLine := currentLine + ' ';
        Inc(currentLength);
      end;
      currentLine := currentLine + words[i];
      Inc(currentLength, wordLen);
    end;
  end;

  { Push the last line if not empty }
  if currentLine <> '' then
  begin
    Inc(lineCount);
    lines[lineCount] := currentLine;
  end;
end;

var
  words: TStringArray;
  lines: TLineArray;
  wordCount, lineCount, i: integer;
  maxWidth: integer;

begin
  { Initialize words }
  wordCount := 8;
  words[1] := 'This';
  words[2] := 'is';
  words[3] := 'a';
  words[4] := 'programming';
  words[5] := 'example';
  words[6] := 'of';
  words[7] := 'text';
  words[8] := 'wrapping';

  maxWidth := 12;

  FormatLines(words, wordCount, maxWidth, lines, lineCount);

  for i := 1 to lineCount do
    writeln('"', lines[i], '"');
end.




(*
run:

"This is a"
"programming"
"example of"
"text"
"wrapping"

*)


 



answered Dec 2, 2025 by avibootz

Related questions

...