How to wrap a string into lines of width w in VB.NET

1 Answer

0 votes
Imports System
Imports System.Text

' This program wraps a string into lines of maximum width w.
'
' Method:
' - Split the input text into words using String.Split().
' - Build each line until adding another word would exceed the width.
' - When the limit is reached, store the line and begin a new one.
' - Uses StringBuilder for efficient string construction.

Module WrapText

    ' Function that wraps text into lines of width w
    Function WrapText(text As String, w As Integer) As String
        Dim words() As String = text.Split({" "}, StringSplitOptions.RemoveEmptyEntries)
        Dim line As New StringBuilder()
        Dim result As New StringBuilder()

        For Each word As String In words

            ' If line is empty, start it with the word
            If line.Length = 0 Then
                line.Append(word)

            Else
                ' Check if adding the next word exceeds width
                If line.Length + 1 + word.Length <= w Then
                    line.Append(" "c).Append(word)
                Else
                    ' Store the completed line
                    result.AppendLine(line.ToString())
                    line.Clear()
                    line.Append(word)
                End If
            End If
        Next

        ' Add the final line
        If line.Length > 0 Then
            result.Append(line.ToString())
        End If

        Return result.ToString()
    End Function

    Sub Main()
        Dim sample As String =
            "VB.NET provides useful built-in tools for handling strings. " &
            "This program demonstrates how to wrap text cleanly and efficiently."

        Dim wrapped As String = WrapText(sample, 35)
        Console.WriteLine(wrapped)
    End Sub

End Module


' run:
'
' VB.NET provides useful built-in
' tools for handling strings. This
' program demonstrates how to wrap
' text cleanly and efficiently.
'

 



answered 3 hours ago by avibootz
edited 2 hours ago by avibootz
...