Computer >> Computer tutorials >  >> Programming >> C#

Removing whitespaces using C# Regex


Let’s say we want to remove whitespace from the following string str1.

string str1 = "Brad Pitt";

Now, use Regex Replace to replace whitespace with empty. Here, we have used System.Text.RegularExpressions.

string str2 = System.Text.RegularExpressions.Regex.Replace(str1, @"\s+", "");

Let us see the complete example.

Example

using System;
using System.Text.RegularExpressions;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         string str1 = "Brad Pitt";
         Console.WriteLine(str1);
         string str2 = System.Text.RegularExpressions.Regex.Replace(str1, @"\s+", "");
         Console.WriteLine(str2);
      }
   }
}

Output

Brad Pitt
BradPitt