Remove excess white space from string

偶尔善良 提交于 2019-12-05 05:15:23

You can use a simple regular expression for that:

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

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.

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.

Try this:

Dim output As String = Regex.Replace("The   Quick          Brown Fox","\\s+" , " ")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!