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

 Live Demo

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

Updated on: 23-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements