Regex.Replace
, spacesRegex.Replace
can act upon spaces. It can merge multiple spaces in a string
to one space. We use a pattern to change multiple spaces to single spaces.
The characters "\s+" come in handy. This means "one or more whitespace characters—so we can replace 1 or more whitespace with just 1.
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.
CollapseSpaces()
can solve that problem but results in even more complexity in the program.using System; using System.Text.RegularExpressions; class Program { static string CollapseSpaces(string value) { return Regex.Replace(value, @"\s+", " "); } static void Main() { string value = "Dot Net Perls"; Console.WriteLine(CollapseSpaces(value)); value = "Dot Net\r\nPerls"; Console.WriteLine(CollapseSpaces(value)); } }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.
string
constructor to convert the character array back to a string
.We saw a whitespace-processing method that uses the Regex.Replace
method. This method can process strings that are slightly invalid. It works well but increases overall complexity.