Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing multiple spaces into just one? [duplicate]

Tags:

vb.net

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?

like image 903
bloodless2010 Avatar asked Jan 07 '14 16:01

bloodless2010


2 Answers

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))
like image 196
Katie Kilian Avatar answered Nov 18 '22 16:11

Katie Kilian


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

s = Regex.Replace(s, " {2,}", " ")
like image 41
Guffa Avatar answered Nov 18 '22 16:11

Guffa