C# Trim with Examples

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:

  1. using System;
  2. namespace CSharpTrimExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string str = " Learn C# programming online! ";
  9. Console.WriteLine(str.Trim()); //Learn C# programming online!
  10. }
  11. }
  12. }

Output:

Learn C# programming online!

Removing leading whitespace with TrimStart()

TrimStart removes leading whitespace from a string.

Syntax:

string.TrimStart()

Sample code:

  1. using System;
  2. namespace CSharpTrimExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string str = " Learn C# programming online! ";
  9. Console.WriteLine(str.TrimStart());
  10. }
  11. }
  12. }

Output:

Learn C# programming online! 

Removing trailing spaces with TrimEnd()

TrimEnd removes trailing whitespace from a string.

Syntax:

string.TrimEnd()

Sample code:

  1. using System;
  2. namespace CSharpTrimExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string str = " Learn C# programming online! ";
  9. Console.WriteLine(str.TrimEnd());
  10. }
  11. }
  12. }
  13.  

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:

  1. using System;
  2. namespace CSharpTrimExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. string str = "##<=Learn C# programming online!=>###";
  9. char[] charArr = "##".ToCharArray();
  10. Console.WriteLine(str.Trim(charArr));
  11. }
  12. }
  13. }

Output:

<=Learn C# programming online!=>

See also:
C# List Contains with Examples
C# typeof with Examples
C# TryParse (int, double, float) with Examples
C# Data Types
C# Variables