Removing whitespace from a string with C# Trim
This tutorial shows you how to remove leading and trailing whitespace in a string using the string Trim method in C#.
More C# tutorials:
Removing leading and trailing whitespace with the string Trim() method
Syntax:
string.Trim()
- Removes leading and trailing spaces in a string
- If there are multiple spaces, multiple spaces are removed
- Whitespace at other than the beginning and end of a string is not removed
Here is a sample cod of removing leading and trailing whitespace from a string:
using System; namespace CSharpTrimExample { class Program { static void Main(string[] args) { string str = " Learn C# programming online! "; Console.WriteLine(str.Trim()); //Learn C# programming online! } } }
Output:
Learn C# programming online!
Removing leading whitespace with TrimStart()
TrimStart removes leading whitespace from a string.
Syntax:
string.TrimStart()
Sample code:
using System; namespace CSharpTrimExample { class Program { static void Main(string[] args) { string str = " Learn C# programming online! "; Console.WriteLine(str.TrimStart()); } } }
Output:
Learn C# programming online!
Removing trailing spaces with TrimEnd()
TrimEnd removes trailing whitespace from a string.
Syntax:
string.TrimEnd()
Sample code:
using System; namespace CSharpTrimExample { class Program { static void Main(string[] args) { string str = " Learn C# programming online! "; Console.WriteLine(str.TrimEnd()); } } }
Output:
Learn C# programming online!
Removing specific characters at the beginning and end with Trim()
string.Trim(params char[] trimChars)
Here is a sample that removes certain characters from the beginning and the end:
using System; namespace CSharpTrimExample { class Program { static void Main(string[] args) { string str = "##<=Learn C# programming online!=>###"; char[] charArr = "##".ToCharArray(); Console.WriteLine(str.Trim(charArr)); } } }
Output:
<=Learn C# programming online!=>