maria
maria

Reputation: 81

Remove excess white space from string

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

Upvotes: 8

Views: 22358

Answers (4)

bhamby
bhamby

Reputation: 15450

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.

Upvotes: 8

SWeko
SWeko

Reputation: 30892

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.

Upvotes: 5

Chandu
Chandu

Reputation: 82903

Try this:

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

Upvotes: 3

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158309

You can use a simple regular expression for that:

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

Upvotes: 25

Related Questions