Simple task - replace all sequential whitespace (tabs, spaces, newlines) with your character of choice, usually a space.
Fact - StackOverflow is on top in google results, when searching for “C# normalize whitespace”.
- How to replace multiple white spaces with one white space
- c# Fastest way to remove extra white spaces
Why this article? Highest voted answers are not the best performing, and some answers are just wrong.
I propose a solution which is based on this StackOverflow answer. Referenced answer has a problem - it fails when input = " " (single space).
I wasn’t sure about it being the only unhandled corner case, so I changed method to use StringBuilder, to simplify string manipulation. Probably the same level of performance, just easier to read.
Below version should be much faster than using Regex (link 1 - highest voted) and slightly faster than NormalizeWithSplitAndJoin by @JonSkeet.
|
|