word wrap in Console app

Recently I found myself working on some player messages (for HA!) and was less than thrilled with how words were getting chopped in half on the linebreak. I came up with this fairly tidy vb.net solution:

1. Build the sentence(s) as normal, with proper spacing and punctuation, and store them all in one long string variable. 

Dim strMessage As String
strMessage = "The smelly kobold swings his broken dagger at you. You see a door opening. You cleave the smelly kobold in two."

2. Dim a string array and split your message variable on the space character. 

Dim strMessageChop() As String
strMessageChop = Split(strMessage, " ")

3. Now we'll re-use the original message variable to contain our modified string. Check the length of the recreated message after each word and insert a linebreak before the word that would cause us to go over 80 characters.

strMessage = ""
Dim intCtr, intLine As Integer

For intCtr = 0 To strMessageChop.Length - 1  strMessage &= strMessageChop(intCtr) & " "

  ' add 1 to account for the space between each word  intLine += (strMessageChop(intCtr).Length + 1)

  If intCtr < strMessageChop.Length - 1 Then    If intLine + strMessageChop(intCtr + 1).Length >= 79 Then      strMessage &= vbCrLf      intLine = 0    End If  End If
Next

4. Then display your newly word-wrapped string however you like (i.e. Console.Writeline or whatever). You can also adjust the point where you word wrap by changing the 79 to something smaller.

This article is part of the GWB Archives. Original Author: Chris G. Williams

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.