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
RT @CodeSnippetsNET: How to replace multiple spaces with a single space in c# or http://t.co/kHX7DnM7HP http://t.co/KmAlw20n0z
RT @CodeSnippetsNET: How to replace multiple spaces with a single space in c# or http://t.co/kHX7DnM7HP http://t.co/KmAlw20n0z