Friday, November 5, 2010

Remove double or single spaces from a string in C#

I have been tidying some data with double spaces in the records. The following function will remove double or triple spaces from a string and replace with just single spaces:

private string RemoveDoubleSpaces(string InputString)
{
string toReturn = InputString;

while (toReturn.Contains("  "))
{
//remove any double , triple spacing
toReturn = toReturn.Replace("  ", " ");
}

return toReturn;
}