To replace multiple spaces with a single space in c# or vb.net you can use a Regular Expression

Sample c#

var inputString = "This  is    a Text with    too much     spaces   in   it!!!";
inputString = Regex.Replace(inputString, @"[ ]{2,}", @" ", RegexOptions.None);

Sample VB.NET

Dim inputString = "This  is    a Text with    too much     spaces   in   it!!!"
inputString = Regex.Replace(inputString, "[ ]{2,}", " ", RegexOptions.None)

there are more ways to do that, but i personally prefer the regex way.
A other way to archieve that would be to use a loop. The snippet below is replacing double spaces until there are no double spaces left.

 

Sample c#

var inputString = "This  is    a Text with    too much     spaces   in   it!!!";
while (inputString.Contains(@"  "))
{
    inputString = inputString.Replace(@"  ", @" ");
}

Sample VB.NET

Dim inputString = "This  is    a Text with    too much     spaces   in   it!!!"
While inputString.Contains("  ")
	inputString = inputString.Replace("  ", " ")
End While

playing with the RegexOptions can speed up or slow down the regex snippet a bit, see RegexOptions Enumeration in the MSDN

2 thought on “How to replace multiple spaces with a single space in c# or vb.net”

Leave a Reply