Remove excess white space from a string

I want to remove extra spaces with VB.net

ex.

"The Quick Brown Fox" 

I need a conclusion

 "The Quick Brown Fox" 

Thank inchika

+7
source share
4 answers

To do this, you can use a simple regular expression:

 Dim cleaned As String = Regex.Replace(input, "\s{2,}", " ") 
+22
source

I understand that this question is quite old, but there is another option that does not include Regex or manual loop through the string and replaces:

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

And the equivalent of C #:

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

Using "null" as the separator character on String.Split , for the split character, all characters that return true if they were sent to Char.IsWhiteSpace . Thus, calling the method this way will divide your string into all spaces, delete the empty strings, then reattach them along with one space between each element of the split array.

+6
source

What you really want is to stitch any multiple empty space into one space, and one way to do this is to find two spaces and replace them with one space until there are two adjacent spaces left, something like this is:

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

However, this is not flawless due to some ideographic limitations of .NET strings , it can go into an infinite loop, but only for some very odd inputs.


EDIT: this particular processing is faster (and easier) using a regular expression, as indicated in the answers.

+4
source

Try the following:

 Dim output As String = Regex.Replace("The Quick Brown Fox","\\s+" , " ") 
+3
source

All Articles