Introduction
This is just a little extension method you can use to word wrap text to a specified column width.
Coding this Mess
Using this is pretty simple. You just call the WordWrap() extension method and pass it the column width you'd like.
using System;
using WW;
namespace WordWrapDemo
{
class Program
{
static void Main()
{
var text = "The quick brown fox jumped over the lazy dog";
Console.WriteLine(text.WordWrap(10));
}
}
}
This will word wrap the text clamping to 10 characters in width.
Limitations
- If you have a single word that is greater than the specified column width, it will overrun the column boundary to the right. This is the only case where your text might "spill over" beyond the width specified. This is by design. There's no great way to handle it. The other options would have been to truncate the word, or to hard break the word in the middle of it somewhere.
- Unfortunately, this does not preserve whitespace, except line breaks. Tabs will be converted to spaces and multiple characters of whitespace will be turned into a single space. Making this preserve whitespace greatly increases the complexity so I decided not to do it.
History
- 16th June, 2020 - Initial submission