Let's say I have a string such as:
"Hello how are you doing?"
I would like a function that turns multiple spaces into one space.
So I would get:
"Hello how are you doing?"
I know I could use regex or call
string s = "Hello how are you doing?".replace(" "," ");
But I would have to call it multiple times to make sure all sequential whitespaces are replaced with only one.
Is there already a built in method for this?
A fast extra whitespace remover... This is the fastest one and is based on Felipe Machado's in-place copy.
The benchmarks...
InPlaceCharArraySpaceOnly by Felipe Machado on CodeProject 2015 and modified by Sunsetquest for multi-space removal. Time: 3.75 Ticks
InPlaceCharArray by Felipe Machado 2015 and slightly modified by Sunsetquest for multi-space removal. Time 6.50 Ticks (supports tabs also)
SplitAndJoinOnSpace by Jon Skeet. Time: 13.25 Ticks
StringBuilder by fubo Time: 13.5 Ticks (supports tabs also)
Regex with compile by Jon Skeet. Time: 17 Ticks
StringBuilder by David S 2013 Time: 30.5 Ticks
Regex with non-compile by Brandon Time: 63.25 Ticks
StringBuilder by user214147 Time: 77.125 Ticks
Regex with non-compile Tim Hoolihan Time: 147.25 Ticks
The Benchmark code...
}
Benchmark notes: Release Mode, no-debugger attached, i7 processor, avg of 4 runs, only short strings tested
Here is the Solution i work with. Without RegEx and String.Split.
so you can:
VB.NET
C#
Enjoy the power of LINQ =D
A regular expressoin would be the easiest way. If you write the regex the correct way, you wont need multiple calls.
Change it to this:
While the existing answers are fine, I'd like to point out one approach which doesn't work:
This can loop forever. Anyone care to guess why? (I only came across this when it was asked as a newsgroup question a few years ago... someone actually ran into it as a problem.)