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
try this method
use it like this:
It's much simpler than all that:
Old skool:
I like to use:
Since it will catch runs of any kind of whitespace (e.g. tabs, newlines, etc.) and replace them with a single space.
This is a shorter version, which should only be used if you are only doing this once, as it creates a new instance of the
Regex
class every time it is called.If you are not too acquainted with regular expressions, here's a short explanation:
The
{2,}
makes the regex search for the character preceding it, and finds substrings between 2 and unlimited times.The
.Replace(temp, " ")
replaces all matches in the string temp with a space.If you want to use this multiple times, here is a better option, as it creates the regex IL at compile time:
Consolodating other answers, per Joel, and hopefully improving slightly as I go:
You can do this with
Regex.Replace()
:Or with
String.Split()
: