DelphiBasics
WrapText
Function
Add line feeds into a string to simulate word wrap SysUtils unit
1 function WrapText(const SourceString {, MaxColumnSize Integer = 45}):string;
2 function WrapText (const SourceString, BreakString string; BreakSet TSysCharSet; MaxColumnSize Integer:string;
Description
The WrapText function effectively splits a line of text SourceString into multiple lines in the returned string.
 
In actual fact, it simply inserts line breaks into the returned string, so that a display of the string would show as multiple lines.
 
Version 1
 
Is the simplest version, allowing a default line break substring (#13#10 - Carriage return + line feed) to be inserted after each set of words fitting MaxColumnSize characters is encountered in the source string. If the max column size is omitted, it defaults to 45.
 
Version 2
 
Allows the inserted line break characters BreakString to be inserted after the occurence of a character in the BreakSet is encountered before MaxColumnSize is reached.
 
If none found BreakString is inserted anyway.
 
In both cases, words are preserved - never split across lines.
Related commands
ConcatConcatenates one or more strings into one string
CopyCreate a copy of part of a string or an array
DeleteDelete a section of characters from a string
InsertInsert a string into another string
MoveCopy bytes of data from a source to a destination
StringOfCharCreates a string with one character repeated many times
StringReplaceReplace one or more substrings found within a string
 Download this web site as a Windows program.




 
Example code : Illustrate the simple version
var
  before, after : string;

begin
  // Set up a long string
  before := 'This is quite a long string, at least 50 chars long';

  // Split it into multiple lines, each 10 characters long
  after := WrapText(before, 10);

  // Show the before and after strings
  ShowMessage(before);
  ShowMessage('');
  ShowMessage(after);
end;
Show full unit code
  This is quite a long string, at least 50 chars long
  
  This is
  quite a
  long
  string,
  at least
  50 chars
  long
 
Example code : Wrap on a special control letter
var
  before, after : string;

begin
  // Set up a long string
  before := 'Ten = 10. Eleven = 11. One hundred = 100.';

  // Split it into multiple lines, terminated by a dot
  after := WrapText(before, #13#10, ['.'], 1);

  // Show the before and after strings
  ShowMessage(before);
  ShowMessage('');
  ShowMessage(after);
end;
Show full unit code
  Ten = 10. Eleven = 11. One hundred = 100.
  
  Ten = 10.
  Eleven = 11.
  One hundred = 100.
 
Delphi Programming © Neil Moffatt . All rights reserved.  |  Home Page