Wednesday, July 06, 2005

Line Break/Word Wrap Algorithm

Anyone know of a good Line Break/Word Wrap algorithm? Word Wrapping is something that I take for granted, since most Windows UI elements take care of it for me (i.e., textbox, web browser, etc).

I wanted my console application to wrap at 80 characters, but my 5 minutes of searching didn't return anything especially useful or simple.

I wrote the following, but I'm sure it can be done better somehow:


string[] blocks = text.Split("\n".ToCharArray());

for (int i = 0; i < blocks.Length - 1; i++)
{
if (blocks[i].Length < m_width)
{
Console.WriteLine(blocks[i]);
}
else
{
int j = 0;
while (j < blocks[i].Length)
{
string tmp = blocks[i].Substring(j).TrimStart();

if (tmp.Length > m_width)
tmp = tmp.Substring(0, m_width);

int k = tmp.LastIndexOfAny(",.?!- ".ToCharArray()) + 1;

if (k == 0)
{
k = tmp.Length;
}

Console.WriteLine(tmp.Substring(0, k));

j += k;

}
}
}


By the way, there's an improved version at:

http://jasonf-blog.blogspot.com/2005/07/word-wrap-version-2.html