remove first occurence white spaces

amitguitarplayer

Active member
Joined
Jul 5, 2008
Messages
27
Programming Experience
5-10
Hi guys,

I have a string "This is a String"

between each word there are 2 white spaces, how can trim the string so there is only One white space between each word so it looks like..

VB.NET:
"This is a String"
instead of
VB.NET:
"This  is  a  String"

thanx a lot guys !!
 
Hi,

This will even work with more than two spaces :

VB.NET:
    Public Function RemoveDoubleSpaces(ByVal MyText As String) As String
        Dim Temp As String = ""
        Dim SpaceAlreadyFound As Boolean = False 'Flag
        For Each c As Char In MyText
            If c = " " Then
                'Found a space
                If Not SpaceAlreadyFound Then
                    'Ok if it is the first
                    Temp += c
                    SpaceAlreadyFound = True
                End If
                'Ignored if not
            Else
                'Other character found, reset flag
                SpaceAlreadyFound = False
                Temp += c
            End If
        Next
        Return Temp.TrimEnd(" ") 'If there were only one space at the end
    End Function
 
An alternative:
VB.NET:
Function RemoveDuplicateSpaces(ByVal str As String) As String
    Do Until str.IndexOf("  ") = -1
        str = str.Replace("  ", " ")
    Loop
    Return str.Trim
End Function
 
Back
Top