Line wrapping at word boundaries for console applications in C#

I didn’t like any of the solutions floating around the web for displaying blocks of text wrapped at word boundaries, so I wrote one.

This:

This is a really long line of text that shoul
dn't be wrapped mid-word, but is

Becomes this:

This is a really long line of text that
shouldn't be wrapped mid-word, but is

Here it is:

public static string GetWordWrappedParagraph(string paragraph)
{
    if (string.IsNullOrWhiteSpace(paragraph))
    {
        return string.Empty;
    }
 
    var approxLineCount = paragraph.Length / Console.WindowWidth;
    var lines = new StringBuilder(paragraph.Length + (approxLineCount * 4));
 
    for (var i = 0; i < paragraph.Length;)
    {
        var grabLimit = Math.Min(Console.WindowWidth, paragraph.Length - i);
        var line = paragraph.Substring(i, grabLimit);
 
        var isLastChunk = grabLimit + i == paragraph.Length;
 
        if (isLastChunk)
        {
            i = i + grabLimit;
            lines.Append(line);
        }
        else
        {
            var lastSpace = line.LastIndexOf(" ", StringComparison.Ordinal);
            lines.AppendLine(line.Substring(0, lastSpace));
 
            //Trailing spaces needn't be displayed as the first character on the new line
            i = i + lastSpace + 1;
        }
    }
    return lines.ToString();
}

Leave a Reply

Your email address will not be published. Required fields are marked *