8

I want to remove the excess white spaces using VB.net

ex.

"The   Quick          Brown Fox"

I want output

"The Quick Brown Fox"

Thanks, inchika

Theraot
  • 31,890
  • 5
  • 57
  • 86
maria
  • 81
  • 1
  • 1
  • 2

4 Answers4

25

You can use a simple regular expression for that:

Dim cleaned As String = Regex.Replace(input, "\s{2,}", " ")
Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
7

I realize that this question is fairly old, but there is another option that doesn't involve Regex, or manually looping through the string and replacing:

Private Function StripSpaces(input As String) As String
    Return String.Join(" ", input.Split(New Char() {}, StringSplitOptions.RemoveEmptyEntries))
End Function

And the C# equivalent:

private string StripSpaces(string input)
{
    return string.Join(" ", input.Split((char[])null, StringSplitOptions.RemoveEmptyEntries));
}

Using a "null" value as the split character on String.Split causes the split character to be all characters that return true if they were sent to Char.IsWhiteSpace. Therefore, calling the method this way will split your string on all whitespace, remove the empty strings, then re-join it together with a single space in between each split array element.

bhamby
  • 15,112
  • 1
  • 45
  • 66
5

What you actually want is to compact any multiple white space to a single space, and one way to do that is to search for two spaces and replace them with a single space, until there are no two adjascent spaces left, something like this:

   Dim myString As String = "The   Quick     Brown     Fox"
   While myString.IndexOf("  ") <> -1
       myString = myString.Replace("  ", " ")
   End While
   Console.WriteLine(myString)

However, this is not fool-proof because of some ideosyncracies of .net strings, this might go into an endless loop, but only for some very odd inputs.


EDIT: This particular processing is faster (and simpler) using a regular expression, as pointed in the othe answers.

SWeko
  • 30,434
  • 10
  • 71
  • 106
3

Try this:

Dim output As String = Regex.Replace("The   Quick          Brown Fox","\\s+" , " ")
Chandu
  • 81,493
  • 19
  • 133
  • 134