 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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();       }    } }Advertisements
 