Remove extra white-spaces within a string

March 07, 2011 C# Regular expressions Snippet
Sometimes the trim function isn't enough. Say that you have a string looking like:
"    this    is  a test     string   "

Using Trim() would get rid of the extra white spaces in the beginning and the end, but it would still leave you with:
"this    is  a test     string"

So how to handle all extra white spaces, even those within the string? We'll lets use some regular expression for that:
using System.Text.RegularExpressions;
...

// Remove extra white-spaces within a string
text = Regex.Replace(text, @"\s+", " ");

Related posts: