
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 Leading and Trailing Spaces 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