44

How do you remove spaces from a string in VB.NET?

8 Answers 8

90

To remove ALL spaces:

 myString = myString.Replace(" ", "")

To remove leading and trailing spaces:

myString = myString.Trim()

Note: this removes any white space, so newlines, tabs, etc. would be removed.

3
  • 3
    .Trim removes white-space characters. Might not be what he wants. Oct 29, 2009 at 18:13
  • 4
    Replace(" ", vbNullString) may run a hair faster, and (more importantly) be a bit clearer. YMMV.
    – Thom Smith
    Oct 29, 2009 at 18:16
  • 4
    I think vbNullstring is a hold over from pre .net days. String.Empty is maybe the more contemporary keyword.
    – ChatGPT
    Oct 31, 2012 at 17:55
23

2015: Newer LINQ & lambda.

  1. As this is an old Q (and Answer), just thought to update it with newer 2015 methods.
  2. The original "space" can refer to non-space whitespace (ie, tab, newline, paragraph separator, line feed, carriage return, etc, etc).
  3. Also, Trim() only remove the spaces from the front/back of the string, it does not remove spaces inside the string; eg: " Leading and Trailing Spaces " will become "Leading and Trailing Spaces", but the spaces inside are still present.

Function RemoveWhitespace(fullString As String) As String
    Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function

This will remove ALL (white)-space, leading, trailing and within the string.

18

"Spaces" in the original post could refer to whitespace, and no answer yet shows how to remove ALL whitespace from a string. For that regular expressions are the most flexible approach I've found.

Below is a console application where you can see the difference between replacing just spaces or all whitespace.

You can find more about .NET regular expressions at http://msdn.microsoft.com/en-us/library/hs600312.aspx and http://msdn.microsoft.com/en-us/library/az24scfc.aspx

Imports System.Text.RegularExpressions
Module TestRegExp
    Sub Main()
        ' Use to match all whitespace (note the lowercase s matters)
        Dim regWhitespace As New Regex("\s")

        ' Use to match space characters only
        Dim regSpace As New Regex(" ")

        Dim testString As String = "First Line" + vbCrLf + _
        "Second line followed by 2 tabs" + vbTab + vbTab + _
        "End of tabs"

        Console.WriteLine("Test string :")
        Console.WriteLine(testString)

        Console.WriteLine("Replace all whitespace :")
        ' This prints the string on one line with no spacing at all
        Console.WriteLine(regWhitespace.Replace(testString, String.Empty))

        Console.WriteLine("Replace all spaces :")
        ' This removes spaces, but retains the tabs and new lines
        Console.WriteLine(regSpace.Replace(testString, String.Empty))

        Console.WriteLine("Press any key to finish")
        Console.ReadKey()
    End Sub
End Module
15

To trim a string down so it does not contain two or more spaces in a row. Every instance of 2 or more space will be trimmed down to 1 space. A simple solution:

While ImageText1.Contains("  ")                     '2 spaces.
    ImageText1 = ImageText1.Replace("  ", " ")      'Replace with 1 space.
End While
0
5

What about Regex.Replace solution?

myStr = Regex.Replace(myStr, "\s", "")
3

This will remove spaces only, matches the SQL functionality of rtrim(ltrim(myString))

Dim charstotrim() As Char = {" "c}
myString = myString .Trim(charstotrim) 
2

You can also use a small function that will loop through and remove any spaces.

This is very clean and simple.

Public Shared Function RemoveXtraSpaces(strVal As String) As String
     Dim iCount As Integer = 1
     Dim sTempstrVal As String

     sTempstrVal = ""

     For iCount = 1 To Len(strVal)
        sTempstrVal = sTempstrVal + Mid(strVal, iCount, 1).Trim
     Next

     RemoveXtraSpaces = sTempstrVal

     Return RemoveXtraSpaces

End Function
2
  • 1
    Not the downvoter, but that's completely overkill, and counterproductive. You concatenate one character at a time, calling Trim every time? Just use the accepted answer. Aug 17, 2012 at 20:39
  • 1
    I would like to defend this answer as it provides a means to loop through the strings from one end or the other, to only remove a space in a given location within the string rather than all spaces. It may have value to someone looking to perform some clean up without taking out all spaces.
    – htm11h
    Apr 23, 2013 at 15:59
0

Try this code for to trim a String

Public Function AllTrim(ByVal GeVar As String) As String
    Dim i As Integer
    Dim e As Integer
    Dim NewStr As String = ""
    e = Len(GeVar)
    For i = 1 To e
        If Mid(GeVar, i, 1) <> " " Then
            NewStr = NewStr + Mid(GeVar, i, 1)
        End If
    Next i
    AllTrim = NewStr
    ' MsgBox("alltrim = " & NewStr)
End Function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.