How to format an array of strings in lines with maxWidth without breaking the words in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic
Imports System.Text

Module Program

    Function FormatLines(words As List(Of String), maxWidth As Integer) As List(Of String)
        Dim result As New List(Of String)()
        Dim currentLine As New StringBuilder()
        Dim currentLength As Integer = 0

        For Each word As String In words
            Dim wordLen As Integer = word.Length

            ' If adding this word exceeds maxWidth, push current line
            If currentLength + (If(currentLine.Length = 0, 0, 1)) + wordLen > maxWidth Then
                result.Add(currentLine.ToString())
                currentLine.Clear()
                currentLine.Append(word)
                currentLength = wordLen
            Else
                If currentLine.Length > 0 Then
                    currentLine.Append(" ")
                    currentLength += 1
                End If
                currentLine.Append(word)
                currentLength += wordLen
            End If
        Next

        ' Push the last line if not empty
        If currentLine.Length > 0 Then
            result.Add(currentLine.ToString())
        End If

        Return result
    End Function

    Sub Main()
        Dim words As New List(Of String) From {
            "This", "is", "a", "programming", "example", "of", "text", "wrapping"
        }
        Dim maxWidth As Integer = 12

        Dim lines As List(Of String) = FormatLines(words, maxWidth)

        For Each line As String In lines
            Console.WriteLine("""" & line & """")
        Next
    End Sub

End Module


	
' run:
'
' "This is a"
' "programming"
' "example of"
' "text"
' "wrapping"
' 

 



answered Dec 2, 2025 by avibootz

Related questions

...