c# Fastest way to remove extra white spaces

Navid Rahmani picture Navid Rahmani · Jun 22, 2011 · Viewed 65.4k times · Source

What is the fastest way to replace extra white spaces to one white space?
e.g.

from

foo      bar 

to

foo bar

Answer

Blindy picture Blindy · Jun 22, 2011

The fastest way? Iterate over the string and build a second copy in a StringBuilder character by character, only copying one space for each group of spaces.

The easier to type Replace variants will create a bucket load of extra strings (or waste time building the regex DFA).

Edit with comparison results:

Using http://ideone.com/NV6EzU, with n=50 (had to reduce it on ideone because it took so long they had to kill my process), I get:

Regex: 7771ms.

Stringbuilder: 894ms.

Which is indeed as expected, Regex is horribly inefficient for something this simple.