11

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?

bloodless2010
  • 349
  • 1
  • 4
  • 15

2 Answers2

24

Use a regular expression to match multiple spaces and replace with a single space:

s = Regex.Replace(s, " {2,}", " ")
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Neat! It works perfectly thank you, all the other code I just found on other threads happens to be really big and bulky which I don't want, this works perfectly, and sorry for the duplicate! – bloodless2010 Jan 07 '14 at 16:53
  • @Guffa, can you please explain the pattern that you used. – MansoorShaikh May 27 '15 at 14:17
  • 1
    @MansoorShaikh: It's just a space followed by the quantifier `{2,}`, so it matches a space, repeated two or more times. – Guffa May 27 '15 at 14:19
8

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))
Katie Kilian
  • 6,815
  • 5
  • 41
  • 64
  • From the answer cited by @TimSchmelter, the RegEx option is faster. Jon Skeet says this approach could create a ton of work for the garbage collector, depending on how long the source string is. – Katie Kilian Jan 07 '14 at 16:58
  • RegEx is rarely faster in my experience. Best to check under load if speed is a factor. IMO Regex should be avoided due to debug/maintainability issues. – rheitzman Jan 07 '14 at 18:19
  • The RegEx solution is faster in this case. See the discussion here: http://stackoverflow.com/a/1280227/645511 I should note that it is very close, depending on the details of exactly what you want. – Katie Kilian Jan 07 '14 at 19:44
  • 2
    I don't doubt it is faster - I wouldn't use it anyway. (One+ too many times trying to reversing engineer RegEx to find other folks problems.) – rheitzman Jan 08 '14 at 22:21
  • 2
    Honestly, that is one of the reasons I took the time to answer this question. I knew the likely answers would center around use of RegEx, and sometimes I *do* use them, but if an easy answer is available that avoids them without causing too many problems, I would lean towards that instead. – Katie Kilian Jan 08 '14 at 22:23