Remove spaces from a string in VB.NET
2015: Newer LINQ & lambda.
- As this is an old Q (and Answer), just thought to update it with newer 2015 methods.
- The original "space" can refer to non-space whitespace (ie, tab, newline, paragraph separator, line feed, carriage return, etc, etc).
- 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.
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.