This program includes the System.Text.RegularExpressions namespace, which gives us easy access to Regex.Replace. In CollapseSpaces, we use the pattern "\s+" to indicate more than one whitespace.
Detail This will match newlines, carriage returns, spaces and tabs. We then replace this pattern with a single space.
Result You can see that the output values only have one space in between the words.
Note Sometimes, after processing text with other regular expressions and methods, multiple spaces will appear.
Tip CollapseSpaces() can solve that problem but results in even more complexity in the program.
static string CollapseSpaces(string value)
return Regex.Replace(value, @"\s+", " ");
static void Main()
string value = "Dot Net Perls";
value = "Dot Net\r\nPerls";
}Dot Net Perls
Dot Net Perls
For performance, it would be better to replace it with a character-based implementation. It is possible to use a character array and then selectively write in characters, omitting unwanted ones.