Replacing multiple spaces with one?

Ok, so I am working on this VB.NET program, and I tried using .replace () to do this, but that is not the best way to do this. I have a string with several spaces between the data that I don't want, which would be the best way to remove spaces from the string, but 1?

+6
source share
2 answers

Use a regex to match multiple spaces and replace it with one space:

s = Regex.Replace(s, " {2,}", " ") 
+12
source

Arrays can be used here if you prefer to avoid regular expressions.

Given this initial line:

 Dim str As String = "This is a test string" 

You can do it:

 Dim arr As String() = str.Split({" "c}, StringSplitOptions.RemoveEmptyEntries) Dim compressedSpaces As String = String.Join(" ", arr) 

You can also combine it into one line:

 Dim newString As String = String.Join(" ", str.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)) 
+5
source

All Articles