Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

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
...