3

I currently have this class to replace consecutive spaces by one:

public static string RemoveSpacesLoop(string value)
{
   if(value.Contains("  "))
   {
       return RemoveSpacesLoop(value.Replace("  ", " "));
   }
   else
   {
       return value;
   }
}

It works, but in the long run it may cause performance issues. is there a way to simplify this ?

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62
user3702989
  • 45
  • 1
  • 7

1 Answers1

7

You can use Regex. For example:

var x = "123  456 789    999   0";
var y = Regex.Replace(x, @"\s{2,}", " ");

It will replace all multiple spaces with single one.

You can also iterate over characters in string and produce new string comparing that characters with spaces something like this:

StringBuilder sb = new StringBuilder();
bool isSpaceFound = false;

foreach (char c in x)
{
    if (c == ' ')
    {
        if (!isSpaceFound)
            sb.Append(c);

        isSpaceFound = true;
    }
    else
    {
        isSpaceFound = false;
        sb.Append(c);
    }
}

var y = sb.ToString();
Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71