Okay, so I am working on this VB.NET program and I have tried using the .replace() to do this but it's not the best way to do this. I have a string with multiple spaces in between data which I don't want, what would be the best way to strip the spaces from the string but 1?
Here's a way using arrays, in case you'd prefer to avoid regular expressions.
Given this starting string:
Dim str As String = "This is a test string"
You can do this:
Dim arr As String() = str.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
Dim compressedSpaces As String = String.Join(" ", arr)
You can also combine it onto one line:
Dim newString As String = String.Join(" ", str.Split({" "c},
StringSplitOptions.RemoveEmptyEntries))
Use a regular expression to match multiple spaces and replace with a single space:
s = Regex.Replace(s, " {2,}", " ")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With