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

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.


Tinggalkan komentar