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

CsharpProgrammingServer Side Programming

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();
      }
   }
}
raja
Published on 14-Aug-2018 16:38:54
Advertisements