Introduction
This is to present an alternative for Word wrap without cutting words. This simplifies the code using string.Split
and LINQ (although I also provide a non-LINQ version for comparison). It also separates the word wrapping funtionality as extension methods in a static class. Finally, I include a WinForms application to demonstrate the code.
Background
The basic idea is to wrap a single line of text (string) to fit a given width, breaking into separate lines only at word boundaries, defined here as "space-delimited". However, the boundary case of a word that is, by itself, longer than the given width is ambiguous. I.e., (a) split the word to fit, or (b) allow single words that are over width. I decided to provide an optional parameter to choose the desired behavior.
The use of string.Split()
reduces apparent complexity (especially in the simple case of allowing overwide words) and avoids character-by-character reprocessing when splitting.
Also, instead of coupling to the WinForms TextRenderer
and Font
classes, the implementation takes a delegate
(Predicate<string>
) that tests if a string "fits". The caller is free to determine fitting by any means desired.
string input = "This is the test string, with some veeerrrryyy looooong words!";
int wrapWidth = 160;
Predicate<string> stringFits = s => TextRenderer.MeasureText(s, font).Width < wrapWidth;
string Ret = input.WordWrap(stringFits, false);
string Ret = input.WordWrap(stringFits);
Points of Interest
There are WordWrapNonLinq()
methods which implement the same functionality without using the Linq .Aggregate()
method. (This demonstrates what the .Aggregate()
is actually doing.)
History
Initial version.