How can I replace multiple spaces in a string with only one space in C#?
Example:
1 2 3 4 5
would be:
1 2 3 4 5
How can I replace multiple spaces in a string with only one space in C#?
Example:
1 2 3 4 5
would be:
1 2 3 4 5
Regex can be rather slow even with simple tasks. This creates an extension method that can be used off of any
string
.It would be used as such:
Another approach which uses LINQ:
no Regex, no Linq... removes leading and trailing spaces as well as reducing any embedded multiple space segments to one space
result:"0 1 2 3 4 5"
I know this is pretty old, but ran across this while trying to accomplish almost the same thing. Found this solution in RegEx Buddy. This pattern will replace all double spaces with single spaces and also trim leading and trailing spaces.
Its a little difficult to read since we're dealing with empty space, so here it is again with the "spaces" replaced with a "_".
The "(?m:" construct enables the "multi-line" option. I generally like to include whatever options I can within the pattern itself so it is more self contained.