Wednesday, July 06, 2005

Word Wrap Version 2

I played around with the word wrap algorithm for a little bit, and came up with the following. I think it's better than my previous code, and simply inserts breaks into a string builder that already contains the text that needs to be split.

One challenge for my scenario is that my text might already have some line breaks in it, and I need to preserve those. Also, the text might have some indenting at the beginning of the line (i.e., spaces after the new line character), and it would be wrong to trim those out.

StringBuilder sb = new StringBuilder(text);

int lastBreak = -1;
int newBreaks = 0;
int lineStart = 0;

for (int i = 0; i < text.Length; i++)
{
if (text[i] == ' ')
{
lastBreak = i;
}
else if (text[i] == '\n')
{
lastBreak = i;
lineStart = i + 1;
}
if (i - lineStart + newBreaks >= m_width)
{
newBreaks++;
sb.Insert(newBreaks + lastBreak, "\n");
lineStart = newBreaks + lastBreak + 1;
}
}

Console.Write(sb.ToString());