- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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(); } } }
- Related Articles
- Trim a string in Java to remove leading and trailing spaces
- How to remove white spaces (leading and trailing) from string value in MongoDB?
- Java Program to remove leading and trailing whitespace from a string
- Java Program to remove the leading and trailing quotes from a string
- How can I remove the leading and trailing spaces both at once from a string by using MySQL LTRIM() and RTRIM() functions?
- How can I remove the leading and trailing spaces both at once from a string without using MySQL LTRIM() and RTRIM() functions?
- How to remove leading and trailing whitespace in a MySQL field?
- MySQL query to remove trailing spaces
- How to remove leading and trailing whitespace from a MySQL field value?
- Remove Leading Zeros from a String in C#
- Remove Trailing Zeros from string in C++
- Split Space Delimited String and Trim Extra Commas and Spaces in JavaScript?
- Python Pandas – Remove leading and trailing whitespace from more than one column
- Remove spaces from std::string in C++
- C++ Program to remove spaces from a string?

Advertisements