How to remove extra whitespace from a string in VB.NET

1 Answer

0 votes
Imports System

Module Program

    ''' <summary>
    ''' Removes leading and trailing whitespace and collapses multiple 
    ''' consecutive whitespace characters into a single space.
    ''' </summary>
    ''' <param name="input">The original string containing extra spaces.</param>
    ''' <returns>A normalized string with single spaces between words.</returns>
    Function RemoveExtraWhitespace(ByVal input As String) As String
        If String.IsNullOrWhiteSpace(input) Then
            Return String.Empty
        End If

        ' Split the string on whitespace characters, automatically stripping out empty entries
        ' created by consecutive spaces or leading/trailing padding.
        Dim words() As String = input.Split(
            CType(Nothing, Char()), 
            StringSplitOptions.RemoveEmptyEntries
        )

        ' Rejoin the extracted words using a single space separator.
        Return String.Join(" ", words)
    End Function

    Sub Main()
        ' Input string containing arbitrary whitespace, tabs, and padding
        Dim s As String = "   This   is   a   test   string   with         extra   spaces.   "

        ' Clean the string using standard framework methods
        Dim cleanedString As String = RemoveExtraWhitespace(s)

        Console.WriteLine(cleanedString)
    End Sub

End Module


' run:
'
' This is a test string with extra spaces.
'

 



answered Aug 7 by avibootz
edited Aug 7 by avibootz
...