Trim (Remove leading and trailing spaces) a string in C#



To trim a string in C#, use regular expression.

Firstly, set the pattern for regex −

string pattern = "\s+";

Let’s say the following is our string with leading and trailing spaces −

string input = " Welcome User ";

Now using Regex, set the pattern and get the result in a new string in C#.

Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement);

The following is the complete example −

Example

using System; using System.Text.RegularExpressions; namespace Demo {    class Program {       static void Main(string[] args) {          string input = " Welcome User ";          string pattern = "\s+";          string replacement = " ";          Regex rgx = new Regex(pattern);          string result = rgx.Replace(input, replacement);          Console.WriteLine("Original String: {0}", input);          Console.WriteLine("Replacement String:{0}", result);          Console.ReadKey();       }    } }
Updated on: 2020-06-21T16:22:39+05:30

899 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements